How I add Headers to http.get or http.post in Typescript and angular 2?

后端 未结 4 2058
后悔当初
后悔当初 2020-12-16 11:35
getHeroes (): Observable {
    return this.http.get(this.heroesUrl)
      .map(this.extractData)
      .catch(this.handleError);
  }

4条回答
  •  無奈伤痛
    2020-12-16 11:52

    I have used below code in Angular 9. note that it is using http class instead of normal httpClient.

    1. so import Headers from the module, otherwise Headers will be mistaken by typescript headers interface and gives error

      import {Http, Headers, RequestOptionsArgs } from "@angular/http";

    2. and in your method use following sample code and it is breaked down for easier understanding.

      let customHeaders = new Headers({ Authorization: "Bearer " + localStorage.getItem("token")});
      const requestOptions: RequestOptionsArgs = { headers: customHeaders };
      return this.http.get("/api/orders", requestOptions);
      

提交回复
热议问题