javascript Angular 2 - 如何在我的标头中编写 Http get 承诺?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33648982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:44:33  来源:igfitidea点击:

Angular 2 - How do I write a Http get promise in my header?

javascriptangular

提问by AngularM

Angular 2 - How do I write a Http get promise?

Angular 2 - 如何编写 Http get 承诺?

I'm importing http and want to set the http header with my auth token. Then I want to write a http get and put the response into a promise to return to the method that calls it.

我正在导入 http 并想使用我的身份验证令牌设置 http 标头。然后我想写一个 http get 并将响应放入一个承诺中,以返回调用它的方法。

So far I have this:

到目前为止,我有这个:

 import {Http, Headers} from "angular2/http";
 import {EnvironmentService} from './environmentService';

 export class AuthService {
     private environmentService: EnvironmentService;
     private http: Http;
     private header: Headers;

     contructor(_environmentService: EnvironmentService, _http: Http, _header: Headers){
         this.environmentService = _environmentService;
         this.http = _http;

         this.header.append('Authorization', '1234');  
         this.header.append('Content-Type', 'application/json');      
     }

     getSpotifyData = ():Promise<Object> => {
         return this.http
           .get('http://ws.spotify.com/search/1/track.json?q=foo',             {headers:this.header})
           .map((response) => {
             return response.json()
           })
           .toPromise();
     }

 }

Thanks in advance!

提前致谢!

回答by alexpods

You can pass headersinto the second argument of http.getmethod and you can use .toPromisemethod to convert an Observableinto a Promise.

您可以传入methodheaders的第二个参数,http.get并且可以使用.toPromisemethod 将 an 转换Observable为 a Promise

export class AuthService {
  // ...

  testApiCall(): any {
    return this.http
      .get('http://localhost:3333/api/', { 
        headers: {
          'Authorization': 'BearerTokenGoesHear'
        }
      })
      .map((response) => {
        // some response manipulation
        return response.json()
      })
      .toPromise();
  }
}

Take a look at this example.

看看这个例子