Вставьте токен в заголовок как http-вызов - PullRequest
0 голосов
/ 27 апреля 2018

У меня есть код:

const parameters = 'Account/GetDoctorDetails?userId=' + 63;
this.http.get(`${webserviceUrlLocalHost}` + parameters)
.subscribe(response => {
  console.log('response.json()');
  console.log(response.json());

Я хотел бы вставить в этот вызов токен в вызове GET webapi, поэтому я изменил свой код на:

const headers = new Headers({ 'Authorization': `Bearer ` + token });
const options2 = new RequestOptions({ headers: headers });
return this.http.get('http://localhost:55803/Account/GetDoctorDetails?userId=63', options2)
    .subscribe( response => console.log(response.json())); */

Но функция никогда не вызывается; есть идеи, почему это не работает?

Ответы [ 2 ]

0 голосов
/ 27 апреля 2018
let headers = new HttpHeaders()
            .append('Content-Type', 'application/json')
            .append('Authorization',`Bearer ` + token );
let params = new HttpParams()
                .append('userId', '63')

return new Observable<any>(observer => {
                this.http.get('your-Rest-API-URL', { headers ,params}).subscribe((response) => {
                    observer.next(response);
                    observer.complete();
                }, (error) => { });
            });
0 голосов
/ 27 апреля 2018

попробуйте new HttpHeaders вместо new RequestOptions ( устарело ), из документации :

добавить заголовки, такие как:

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'my-auth-token'
  })
};

поэтому ваш options2 должен быть:

const options2 = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': `Bearer ` + token
  })
};
...