RequestOptions устарела ошибка символа в Angular 5 - PullRequest
0 голосов
/ 23 мая 2018

Я пытаюсь адаптировать код в Angular 4 к Angular 5. Я внес много изменений, но у меня была ошибка около RequestOptions.Код касается аутентификации, и здесь у меня ошибка:

  import { Injectable } from '@angular/core';
   import { RequestOptions} from '@angular/http';
   import {User} from '../model/model.user';
   import 'rxjs/add/operator/map';
    import {HttpClient, HttpHeaders} from '@angular/common/http';

  @Injectable()
  export class AuthService {
  constructor(public http: HttpClient) { }

    public logIn(user: User) {

const headers = new HttpHeaders();
headers.append('Accept', 'application/json')
// creating base64 encoded String from user name and password
const base64Credential: string = btoa( user.username + ':' + user.password);
headers.append('Authorization', 'Basic ' + base64Credential);
     // this is where i'm having a problem : 
      const httpOptions = new RequestOptions();
      httpOptions.headers = headers;

    return this.http.get('http://localhost:8081/' + '/account/login' ,   
   httpOptions)
  .map(resp => {
    // login successful if there's a jwt token in the response
    const user = resp.json().principal; // the returned user object is a principal object
    if (user) {
      // store user details  in local storage to keep user logged in between page refreshes
      localStorage.setItem('currentUser', JSON.stringify(user));
    }
  });
     }


    logOut() {
// remove user from local storage to log user out
return this.http.post('http://localhost:8081/' + 'logout', {} )
  .map(resp => {
    localStorage.removeItem('currentUser');
  });

      }
      }

ошибка: устаревший символ используется, пожалуйста, помогите мне изменить код в Angular 5 (RequestOptions)

1 Ответ

0 голосов
/ 23 мая 2018

Не следует использовать RequestOptions из устаревшего модуля @angular/http.

Как указано в документации API options теперь имеют следующий тип:

{
    headers?: HttpHeaders | {
        [header: string]: string | string[];
    };
    observe?: HttpObserve;
    params?: HttpParams | {
        [param: string]: string | string[];
    };
    reportProgress?: boolean;
    responseType?: 'arraybuffer' | 'blob' | 'json' | 'text';
    withCredentials?: boolean;
}

Таким образом, вы должны написать:

const headers = new HttpHeaders();
headers.append('Accept', 'application/json')
const base64Credential: string = btoa( user.username + ':' + user.password);
headers.append('Authorization', 'Basic ' + base64Credential);

this.http.get('http://localhost:8081/' + '/account/login', {
  headers: headers
});

Или альтернативно:

this.http.get('http://localhost:8081/' + '/account/login', {
  headers: {
    'Accept': 'application/json',
    'Authorization': 'Basic ' + btoa(user.username + ':' + user.password)
  }
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...