Add header to Http, Angular 2, Ionic 2 API request

I have an ionic 2 application (which uses Angular 2 Http), I have code that gets JSON from the API, however I need to send 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 title, however it doesn't work ...

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?

thank

+4
source share
1 answer

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

Also, there is a syntax error in your code. Request parameters - this is the second parameter .get (url, {}), and you wrote: .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");
});
Run codeHide result

Creating explicit request parameters.

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

_http.get(url, opt).
Run codeHide result

:

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

}
Hide result
+6

All Articles