Angular 2 HTTP Get Headers


#1

Hey everyone :slight_smile: sorry to bother you, but I have not been able to find a comprehensible way to use headers with an http get request in angular 2 (I’ve been looking for 2+ days)

this is my code thus far (though, obviously, it does nothing at the moment):

request(value){
    var headers = new Headers();
    headers.append('Authorization', 'Bearer ' + this.token);
    this.http.get( this.URL + "product/" + value, {"Headers": headers})
    .map(
      res => res.json()
    )
    .subscribe(
      data => this.product = JSON.stringify(data),
      err => this.status.error = JSON.stringify(err)
    );
  }

If anyone with experience in this topic would be willing to give some guidance, It would be much appreciated :slight_smile:

Thanks !


#2

First thing that jumps out to me is that you’ve capitalized Headers in the options argument. I think it should just be headers.


#3

No luck there, but thanks for the input :slight_smile:


#4

It would help to know how you are invoking this code, what you are expecting to see, and what you are seeing.


#5

So, the company I work for has recently made an API to view products.
We already have some angular 1 in a web page that is able to successfully retrieve the product, by using a product ID and a JWT token:
$http({ method: 'GET', url: $scope.config.url + 'product/' + $scope.product.id, headers: { 'Authorization': 'Bearer ' + $scope.store.token }, withCredentials: true }).then(function(result) { if (result.data.error) { $scope.status.error = result.data.error; } else if (result.data.products) { $scope.status.error = null; $scope.products = result.data.products; } else { $scope.status.error = result.data; } }

Within the webpage it’s shown with {{products | json}} and has an output like:
[ { “product_id”: “12345”, “title”: “Name of Product”, “show_price”: “true”, “general_images”: [ “00142201005080924314395.jpg” ] } ]

I was able to get a token on an earlier page in the app, which I pushed to this page via NavParam,
and the ‘Value’ in my function is just the product ID that the user is searching for.

I’m attempting to translate it to angular 2, so I can retrieve the product info and display it within a native looking app, but no dice thus far :slight_smile:


#6

Your res object has headers and all response data. Just don’t use .map(res => res.json())


#7

All right, I commented that portion out of the function, as well as added alert functions to the .subscribe portion for success or error. Unfortunately, neither of those alerts pop up when I run the code, so it seems that the problem is still there, and is preventing that portion of the code from running at all.


#8

Where code?

xvxcvcxvcxvxccx


#9

I changed

request(value){ var headers = new Headers(); headers.append('Authorization', 'Bearer ' + this.token); this.http.get( this.URL + "product/" + value, {"Headers": headers}) .map( res => res.json() ) .subscribe( data => this.product = JSON.stringify(data), err => this.status.error = JSON.stringify(err) ); }

into

request(value){ var headers = new Headers(); headers.append('Authorization', 'Bearer ' + this.token); this.http.get( this.URL + "product/" + value, {"headers": headers}) /*.map( res => res.json() )*/ .subscribe( data => alert('data'), //this.product = JSON.stringify(data), err => alert('error') //this.status.error = JSON.stringify(err) ); }

So, I would be able to see if the .subscribe() portion ran, but it doesn’t appear to be


#10

Try check it into dev console -> network. If the request has been sent, and what is response.


#11

Alright, just checked, and the request is not sent


#12

I found the error (i Believe) in the web console:

EXCEPTION: Error: Uncaught (in promise): TypeError: Cannot read property 'get' of undefined

Has anyone seen this one before?


#13

constructor (public http: Http)


#14

You are either not initializing this.http or you are invoking request in a context where this is not what you expect it to be.


#15

OK, so this is what I have thus far in the initialization of Http:

import {Http, Headers} from 'angular2/http';

And

static get parameters() { return [[NavController],[NavParams],[Http]]; }

And

constructor(nav: NavController, params: NavParams, bcScanner: BarcodeScanner, public http: Http) { this.nav = nav; this.params = params; this.picturesPage = PicturesPage; this.token = this.params.get("token") this.bcScanner = bcScanner; this.http = http; }

And the function is within the pages class. I thought I hit all of my bases, but evidently I’m still missing something here :frowning:


#16

Java-like developer detected.

I also find this incredibly unintuitive, but in the land of JavaScript this is not guaranteed to be the object that defines the method (especially if you pass functions around).


#17

OK, I’ll take a look into that :slight_smile: Thanks

(and I’ve never actually used Java, so I almost laughed out loud at that (before I remembered I was in the workplace :wink: )


#18

One other potential area of confusion is whether you’re using TypeScript or JavaScript. If TypeScript, you don’t need that static get parameters method. Don’t know if it would actually cause harm or not, but it might be worth ensuring that the http parameter to the constructor is coming in properly.


#19

I’m using typescript so I’ll check that out :slight_smile: The reason I have it there is because on the previous page, I was using an http post, which absolutely refused to run until I had put it in on that page :slight_smile:


#20

would be a lot easier to debug/resolve if you put the code in plnkr or jsbin