Jeremy Miller Jeremy Miller - 2 months ago 30
JSON Question

Angular 2/4 trying to get Observable with calling a javascript array object - to be subscribed to

I have a Service file that I am trying to set as an observable , with a component that i want to subscribe to it. But it's not working, what am i doing wrong?

Service: Tracker.service.ts

getAllCoins(): (Observable<string>) { //<Response> {
return allC
.map(res => JSON.stringify(res))
//.do(data => console.log('coins ' + JSON.stringify(data)))
//.catch(this.handleError)
}


my function in which this observable of it does not like

Previously i used a REAL URL and I used http.get FYI and that worked ( coded differently though)

My JSON data:

const allC =
[{
"BTC": {
"USD": 3349.1
},
"ETH": {
"USD": 296.3
},
"LTC": {
"USD": 47.56
},
"EOS": {
"USD": 1.83
},
"DASH": {
"USD": 195.83
}
}]


Next I setup component and try to subscribe to it.

Component file

coinsList = [];

constructor(
private coinService: TrackerService
) {
this.coinService.getAllCoins()
.subscribe(
(data) => {
for (let key in data) {
this.coinsList.push({ coinName: key, price: data[key].USD});
}
},
(error) => console.log('error :' + error)

);
}

Answer Source

Pengyy is correct. I don't wish to steal his thunder but I would do as he suggest, but then ALSO (Observable<string>) to (Observable<Response>)

  1. Your component file looks fine
  2. use the Observable.of(allC)
  3. Change to

    getAllCoins(): (Observable<Response>) {   
        return Observable.of(allC)
           .map(res => JSON.stringify(res))
           //.do(data => console.log('coins ' + JSON.stringify(data)))
           //.catch(this.handleError)
    

    }