0

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)

        );
}
0

1 Answer 1

2

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

This is because http.get will return an Observable.


Array.map is different from Observable.map operator.

  • Array.map will return an Array, see here.
  • Observable.map will return an Observable.

You should use Observable.of(arr) to provide an Observable first.

Observable.of(allC)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.