通知组件时服务功能的角度完成 [英] Notify component when service function is complete in angular
问题描述
我写它做一个HTTP查询到后端服务:
I writing a service which do a http query to the backend:
getPlacesForUser(){
this.http.get("http://localhost:8080/processPlaces")
.map(res => res.text())
.subscribe(
data => this.result = data,
err => this.logError(err),
() => console.log('Places Request completed')
)
}
现在我想更新的组件端,如果请求完成:
Now I want to update the components-side, if the request is completed:
processPlaces(){
this._backendService.getPlacesForUser();
}
我怎么能组件和服务之间的沟通?
How can I communicate between the component and service?
此外,我寻找最好的做法。
Furthermore I searching for the best practice.
推荐答案
在事实上,你可以直接从 getPlacesForUser
方法返回observble并在其上附加一个订阅方法
In fact, you can return the observble directly from the getPlacesForUser
method and attach a subscribe method on it.
-
服务
getPlacesForUser(){
return this.http.get("http://localhost:8080/processPlaces")
.map(res => res.text());
}
组件
processPlaces(){
this._backendService.getPlacesForUser()
.subscribe(
data => this.result = data,
err => this.logError(err),
() => console.log('Places Request completed')
);
}
的结果
属性对应,您可以在组件中使用该组件的属性。
The result
attribute corresponds to an attribute of the component you can use in the component.
您可以注意到一个异步
管道可直接利用中前pressions观察到的(例如在一个 ngFor
之一)。
You can notice that a async
pipe is available to directly leverage observable in expressions (for example within an ngFor
one).
我觉得这个答案可以帮助你:<一href=\"http://stackoverflow.com/questions/34450131/how-to-consume-http-component-efficiently-in-angular-2-beta/34450948#34450948\">How在角2公测有效地消耗HTTP组件?。
I think that this answer could help you: How to Consume Http Component efficiently in angular 2 beta?.
希望它可以帮助你,
蒂埃里
Hope it helps you, Thierry
这篇关于通知组件时服务功能的角度完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!