Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 298
AngularM Avatar asked Nov 11 '15 10:11

AngularM


People also ask

How would you make an Angular service return a promise?

How To Create Promises in Angular? To create a promise in Angular we just need to use 'new Promise(function)' syntax. The promise constructor takes function as a parameter and that inner function takes resolve and reject as a params.

How do I add headers in HTTP request in Angular 8?

There are two ways by which we can add the headers. One, we add the HTTP Headers while making a request. The second way is to use the HTTP interceptor to intercept all the Requests and add the Headers. In both cases, we use the httpHeaders configuration option provided by angular HttpClient to add the headers.

What is difference between promise and observable in Angular?

Promises deal with one asynchronous event at a time, while observables handle a sequence of asynchronous events over a period of time. Emit multiple values over a period of time. Emit a single value at a time. Are lazy: they're not executed until we subscribe to them using the subscribe() method.


1 Answers

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.

like image 65
alexpods Avatar answered Sep 29 '22 21:09

alexpods