我从雅虎那里获取天气,我只想从响应中获取一些字段。我认为这可能有用,但它不能如何实现获得响应JSON然后再做一些工作只返回一个带有几个字段的对象?
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;
}
答案 0 :(得分:1)
在transformJson()函数中,使用空对象初始化变量result,并且永远不会为其赋值。最后你返回并清空结果。
答案 1 :(得分:1)
怎么样:
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
};
}