为什么我的页眉在角度7中没有响应?

时间:2019-01-12 10:08:26

标签: angular typescript angular7

MY httpheaderRequestOption在API中无法正常工作。我正在使用Angular 7.1。我已经尝试了所有公式,但没有任何反应。

我遇到此错误:

  

令牌未传递标头

我正在使用以下代码:

import { Http,RequestOptions,Headers } from '@angular/http';
import { keyframes } from '@angular/animations';

@Injectable({
    providedIn: 'root'
})
export class UrlrequestService {
    public headers = new Headers({ 'Content-Type': 'application/json'});
    API:any = "http://api-url";
    constructor(public http: Http) { }

    get(url) {  
        this.headers.set('Authorization','Token  '+localStorage.getItem('token'))
        let options = { headers: this.headers };
        console.log(options)
        return this.http.get(this.API+url,options);
    }

2 个答案:

答案 0 :(得分:0)

对于Angular 7,您应该从HttpClient导入HttpHeaders@angular/common/http。此外,您应该使用Bearer来传递令牌。 尝试类似的事情:

import { HttpClient, HttpHeaders } from '@angular/common/http';

// ...

httpOptions;
api_path:any = "http://api-url";

constructor(public http: Http) {}


// ...
this.httpOptions = {
  headers: new HttpHeaders({
  'Content-Type':  'application/json',
  'Authorization': 'Bearer ' + localStorage.getItem('token')
  })
};

答案 1 :(得分:0)

每次传递HTTP标头时,请记住令牌的类型为Bearer。因此,授权标头行应如下所示:

this.headers.set('Authorization','Bearer '+localStorage.getItem('token'))