如何在此 rxjs 管道中进行进一步处理?

How can I do further processing in this rxjs pipeline?

我正在从 Yahoo 获取天气信息,我只想从响应中获取几个字段。我认为这可能行得通,但行不通 我如何才能获得响应 JSON 然后再做一些工作以仅 return 具有几个字段的对象?

  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;
  }

在您的 transformJson() 函数中,您使用一个空对象初始化变量 result 并且从不为其分配任何值。最后你 return 和空结果。

怎么样:

  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
    };
  }