CarlRyds CarlRyds - 5 months ago 816
JSON Question

Add Header to the API Http request, Angular 2, Ionic 2

I have an ionic 2 app (which uses Angular 2 Http), i have the code which gets the JSON from the API, however i need to send the app-id, app-key and Accept as a header, this is the main code...

import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
import {Http} from 'angular2/http';

@Component({
templateUrl: 'build/pages/latest-page/latest-page.html'
})
export class LatestPage {
static get parameters() {
return [[NavController]];
}

constructor(_navController, http) {

this._navControler = _navController;
this.http = http;

this.http.get("https://twit.tv/api/v1.0/people/77").subscribe(data => {
console.log("Got Data");
this.items = JSON.parse(data._body).people;
}, error => {
console.log("Error with Data");
});

}


And this is how i tried to add the header, however its not working...

constructor(_navController, http) {

this._navControler = _navController;
this.http = http;

var headers = new Headers();
headers.append('app-id', '0000');
headers.append('app-key', 'abc000abc');
headers.append('Accept', 'application/json ');

this.http.get("https://twit.tv/api/v1.0/people/77"),{"Headers": headers}.subscribe (data => {
console.log("Got Data");
this.items = JSON.parse(data._body).people;
}, error => {
console.log("Error with Data");
});

}


Any ideas?

Thanks

Answer

Headers must be set inside the RequestOptions, which is the second parameter http.get()

Besides you have a syntax error in your code. Request options is the second parameter of .get(url, {}), and you wrote like this: .get(url),{}

this.http.get("https://twit.tv/api/v1.0/people/77",{"Headers": headers}).subscribe (data => {
console.log("Got Data");
this.items = JSON.parse(data._body).people;
}, error => {
 console.log("Error with Data");
});

Creating explicitly request options.

let opt: RequestOptions
let myHeaders: Headers = new Headers
myHeaders.set('Content-type', 'application/json')
opt = new RequestOptions({
  headers: myHeaders
})

_http.get(url, opt).

After some misunderstanding, I'll leave here you're own code with my suggestions:

constructor(_navController, http) {
 
/*this isn't necessary, _navController and http are already available for "this. "*/
   this._navControler = _navController;  
   this.http = http;
 
   let opt: RequestOptions
   let myHeaders: Headers = new Headers
   myHeaders.set('app-id', 'c2549df0');
   myHeaders.append('app-key', 'a2d31ce2ecb3c46739b7b0ebb1b45a8b');
   myHeaders.append('Content-type', 'application/json')
   
   opt = new RequestOptions({
     headers: myHeaders
    })   
   
   this.http.get("https://twit.tv/api/v1.0/people/77",opt).subscribe (data => {
     console.log("Got Data");
     this.items = JSON.parse(data._body).people;
   
  }, error => {
    console.log("Error with Data");
  });

}