korovaisdead
korovaisdead

Reputation: 6341

Angular 2. Http map\subscribe issue

want to read json file and build settingsProvider.

So I'm doing it like this:

import {Http} from "angular2/http";
import {Injectable} from "angular2/core";

@Injectable()
export class SettingsProvider{
    url: string = "";
    constructor(http: Http){
        http.request('js/app/config/config.json').map(data => data.json()).subscribe(data => this.url = data.url);
    }

    getUrl():string {
        return this.url;
    }

}

But got an error like this:

enter image description here

So, my first question is - why so?

Second question:

When I'm doing like this:

http.request('js/app/config/config.json').subscribe(data => {
            this.url = data.json().url;
        });

this points not to the class, but to the Subscriber instance. Why so? I thought that "fat-arrow"-lambda in TypeScript help us to get rid of this weird closure.

Upvotes: 2

Views: 1021

Answers (2)

mukund patel
mukund patel

Reputation: 1052

I also get such error to retrieve branch json, so I change in map. I used $.parseJSON(res._body), and it works fine.

getbranch (){ return this.http.get("/branch").map( res => $.parseJSON(res._body) ).subscribe( data => this.branches = data ,error => alert('No data found') )}

Upvotes: 0

Wobbley
Wobbley

Reputation: 914

The Map function needs to be imported from RXJS, try for example:

 import 'rxjs/add/operator/map';

There is no need to do the http request inside the constructor, you should make it it's own method. An example from a while back that I did with the names changed so it makes more sense in your contex:

@Injectable()
export class SettingsProvider{

  constructor(public http: Http) {
  }

  getSettings() {
    //http request code here
  }
}

I can include more code later if you don't get it to work based on this. The import should solve your map problem at least.

Upvotes: 2

Related Questions