【发布时间】:2018-01-27 15:04:39
【问题描述】:
我的服务中有以下 http.get 链:
constructor(private http:Http) {}
getDetails(sysID:string){
var details;
this.http.get('https://blahURL').map(res => res.json().filter(f => f.id == another.id)[0]).subscribe(
(data) => details = data, // Reach here if res.status >= 200 && <= 299
(err) => console.log(err), // Reach here if fails
function(){ // On completion
console.log(this);
this.http.get(...) //<- fails
“完成时”功能被触发,但我在控制台中得到的 this 是一个 SafeSubscriber 对象,因此下一个 http 调用 this.httpfails。
我做错了什么?
【问题讨论】:
-
在 this.http 调用之前,将 this 分配给一个新变量:
let that = this;并在回调中使用that.http.get(...)看看是否有效,它看起来像 这个上下文丢失了 -
我不明白你错误的括号,你有.map(res => res.json().filter,它必须是.map(res => res.json()).filter (...)
-
括号没问题,因为我是直接过滤json(有点不寻常,我知道):)
-
理想情况下,您不应该在 subscribe 中执行此操作。您应该使用 flatmap 或 switchmap
-
如果我使用flatmap,我还能提取
details变量吗?
标签: angular http typescript rxjs