【发布时间】:2017-08-04 18:39:52
【问题描述】:
我正在尝试围绕 Observables 进行思考
这是我目前使用.toPromise 的方法
request.ts
get(url): Promise<any>
{
// HARD CODED A URL I FOUND , NOT USING THE "url" param
return this.http.get("https://conduit.productionready.io/api/profiles/eric").map(response => {
return response.json() || {success: false, message: "No response from server"};
}).catch((error: Response | any) => {
return Observable.throw(error.json());
}).toPromise();
}
这行得通,
从
调用event.service.ts
功能...
this.Request.get("/user").then(response => {
console.log("Got response:", response);
}).catch(error => {
console.log("Got error:", error);
}).then(response => {
console.log("Another response:", response);
}).catch(error => {
console.log("Got another error:", error);
});
相反,我想做的是 Observables
所以
我尝试“订阅”
订阅者
我不太明白如何使用“数据”和“订阅”等。
var url = "https://conduit.productionready.io/api/profiles/eric";
var blah;
this.getDataObservable(url).subscribe(
data => {
blah = data;
console.log("I CANT SEE DATA HERE: ", blah);
}
);
调用函数
getDataObservable(url: string) {
return this.http.get(url)
.map(data => {
data.json();
// the console.log(...) line prevents your code from working
// either remove it or add the line below (return ...)
console.log("I CAN SEE DATA HERE: ", data.json());
return data.json();
});
}
【问题讨论】:
-
无需添加return data.json()
-
问题是我不明白这个,你能写一个答案给我看吗?
-
你确实需要返回
data.json(),或其他任何事情。map只是一个生命周期钩子,您可以使用它来修改流中的值,然后再将其发送给订阅者。看看my answer here,以更好地了解 RxJS 的工作原理。 -
你对代码做了什么,看起来有人审查了它并留下了他/她的 cmets。
-
正确,我把它拿起来尝试使用它......
标签: javascript angular typescript observable