AngularM
AngularM

Reputation: 16628

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

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

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.

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!

Upvotes: 9

Views: 17480

Answers (1)

alexpods
alexpods

Reputation: 48505

You can pass headers into the second argument of http.get method and you can use .toPromise method to convert an Observable into 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.

Upvotes: 12

Related Questions