Add Header to a API call


#1

Hi, I want to put data via JSON from an API, I’m having trouble with sending headers with the API call, as i need to send the app-id and api key with the request, heres my page code…

latest.js

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, Http]];
  }

constructor(_navController, http) {
 
   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");
  });

}

  episodeClick (event, item){
    console.log(item.label);
  }
}

When i try to run ionic serve --lab the terminal gives this error

SyntaxError: /Users/Carl/TwitCasts/app/pages/latest-page/latest-page.js: Unexpected token (18:10) while parsing file: /Users/Carl/TwitCasts/app/pages/latest-page/latest-page.js

That seems to refer to this part of the code…

let opt: RequestOptions
let myHeaders: Headers = new Headers

But i’m not sure what the issue is, anyone got any ideas?

Thanks :slight_smile:


#2

You found some copypasta that is written in TypeScript and tried to feed it to your JavaScript project. I would strongly recommend switching the project to TypeScript.


#3

So, if i transfer it into a TypeScript app, it’ll work fine?


#4

It should, I’m using custom headers in API calls in my typescript project and the structure is similar.