【问题标题】:how i can add token to http get request to rest api我如何将令牌添加到 http get request to rest api
【发布时间】:2018-11-09 16:21:59
【问题描述】:
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)

        )
    }

【问题讨论】:

  • 想详细说明问题,例如说明您面临的问题或出了什么问题?

标签: angular token


【解决方案1】:

不要将您的对象命名为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>;

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

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

顺便说一句#2,你的标题是错误的,因为你问的是 Angular,而不是 AngularJS。

【讨论】:

    猜你喜欢
    • 2019-10-01
    • 1970-01-01
    • 2022-12-01
    • 2014-01-31
    • 2017-12-04
    • 2018-06-15
    • 2020-05-07
    • 2021-06-30
    • 1970-01-01
    相关资源
    最近更新 更多