我指的是这个post这对理解 Observables 非常有帮助,但还有一些我不明白的地方。
在plunker里面吧refers to ,我更改了“src/myfreinds.ts”以查看发生了什么并添加了一些控制台日志:
首先我保持原样:
export class FriendsList{
result:Array<Object>;
constructor(http: Http) {
console.log("Friends are being called");
http.get('friends.json')
.map(response => {
console.log("map");
console.info(response);
response.json(); //MISTAKE WAS HERE SHOULD HAVE HAD "return response.json()" INSTEAD AS EXPLAINED IN THE ANSWER GIVEN
})
.subscribe(result => {
console.log("subscribe");
console.info(result);
this.result =result;
}
);
}
}
在这种情况下,我可以在日志中看到 subscribe
下的 result
是 undefined
。但是 map
下的 response
确实包含响应。
如果我去掉 map
部分并保留 subscribe
部分,如下所示:
export class FriendsList{
result:Array<Object>;
constructor(http: Http) {
console.log("Friends are being called");
http.get('friends.json')
.subscribe(
result => {
console.log("subscribe");
console.info(result);
this.result =result;
}
);
}
}
这一次,在控制台中,我可以在下方看到订阅 result
的详细信息,而不是像我在之前的案例中看到的那样 undefined
。
我想了解为什么订阅,成功函数不包含每次是否应用 map
函数的结果?
最佳答案
subscribe()
作为 result
传递,之前的运算符 .map()
返回 - return response.json()
。
很有可能 response != undefined
但是 response.json() == null
关于angular - Observable:如果在 map() 之前,为什么不导致 subscribe() 成功函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40505691/