Barry
Barry

Reputation: 1820

How can I do further processing in this rxjs pipeline?

I am fetching weather form Yahoo and I want to only grab a few fields out of the response. I thought this might work but it doesn't how can I achieve getting the response JSON and then do some more work to only return an object with a few fields?

  constructor(private http: Http) { }

  getWeather(): Observable<any> {
    return this.http
        .get(this.url)
        .map((resp:Response) => resp.json())
        .switchMap((json) => this.tranformJson(json))
        .catch(this.handleError);
  }

  private tranformJson(json) {
    let result = {};
    const r = json.query.results.channel;
    const current = r.item.condition.temp;
    const f = r.item.forecast[0];
    const { high, low, text} = f;
    result['high'] = high;
    result['low'] = low;
    result['text'] = text;
    result['currentTemp'] = current;
    return result;
  }

Upvotes: 0

Views: 52

Answers (2)

paulpdaniels
paulpdaniels

Reputation: 18663

How about:

  getWeather(): Observable<any> {
    return this.http
        .get(this.url)
        .map((resp:Response) => resp.json())
        //You are only using the channel field so pluck it out
        .pluck('query','results','channel')
        // Use map instead of switchMap
        .map(this.transform)
        .catch(this.handleError);
  }

  private static transform({item: {forecast, condition}}) {
    const [{high, low, text}] = forecast;
    return {
      currentTemp: condition.temp,
      high,
      low,
      text
    };
  }

Upvotes: 1

Yakov Fain
Yakov Fain

Reputation: 12376

In your transformJson() function you initialize the variable result with an empty object and never assign any values to it. In the end you return and empty result.

Upvotes: 1

Related Questions