我如何将令牌添加到http获取休息API的请求

时间:2018-11-09 16:22:00

标签: angular token

export class ProfileService {
    public apiUrl:string='http://xyz/api';

    constructor(private http: HttpClient, private reqHeaders:HttpHeaders) {}

    public getProfile(): Observable<any>
    { 

        var reqHeader = new HttpHeaders({
           'Content-Type':'application/json',
           'Authorization':JSON.parse(localStorage.getItem('token'))
        })
        return this.http.get(this.apiUrl + '/info.json',{reqHeaders}).map(
            (data)=>console.log(data)

        )
    }

1 个答案:

答案 0 :(得分:0)

与其仅命名对象reqHeaders而不是命名对象headers,而是应该可以正常工作。看看get的定义:

get<T>(url: string, options?: {
    headers?: HttpHeaders | {
        [header: string]: string | string[];
    };
    observe?: 'body';
    params?: HttpParams | {
        [param: string]: string | string[];
    };
    reportProgress?: boolean;
    responseType?: 'json';
    withCredentials?: boolean;
}): Observable<T>;

您还可以利用HttpInterceptor向请求(more#1more#2)添加身份验证。

顺便说一句,您不必将Content-Type设置为application/json,因为它是默认值。

通过#2,您的标题是错误的,因为您是在询问Angular,而不是AngularJS。

相关问题