Angular 2 - 如何在标题中编写Http get promise?

时间:2015-11-11 10:49:41

标签: javascript angular

Angular 2 - 如何编写Http get promise?

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

到目前为止我有这个:

 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();
     }

 }

提前致谢!

1 个答案:

答案 0 :(得分:12)

您可以将headers传递给http.get方法的第二个参数,然后您可以使用.toPromise方法将Observable转换为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();
  }
}

看看this example