【发布时间】:2019-01-31 20:36:15
【问题描述】:
我听说建议通过服务(而不是通过组件)发出服务器请求,以便函数的请求可以是可重用的(由另一个组件)。的诅咒,最后,我们需要在组件中的服务器响应。
我的问题是从组件调用服务以获取数据的最佳做法是什么。我问是因为 http 请求将是 Observable 的操作,这意味着它是异步操作。
所以,如果我会这样做:
//data.component.ts
const data = this.httpService.getDataFromTheServer();
//httpService.service.ts
getDataFromTheServer(){
return this.http.post(url).map(
res=>res.json())
}
数据永远不会进入组件的变量。
我对这个问题的解决方案是在另一个“主题”中使用。像这样:
//data.component.ts
this.httpService.getDataFromTheServer()
this.httpService.getData.subscribe(res => {
const data = res;
}
//httpService.service.ts
public getData = new Subject();
getDataFromTheServer(){
return this.http.post(url).map(
res=> this.getData.next(res.json()))
}
像这样它会叉很好。但不确定这是否是解决此问题的最佳做法。
有人有其他想法吗?多谢!
更新
感谢所有受访者。我知道我可以在我的组件中这样做:
this.httpService.getDataFromTheServer().subscribe...
但我想知道我是否可以更多地清洁我的组件,并且只用这个:
const data = this.httpService.getDataFromTheServer()
或者是否有其他清洁组件的方法?或者我可能对“通过服务发出服务器请求”的建议不够了解? 我很乐意解释得更清楚。
【问题讨论】:
-
我认为您缺少 data.component.ts 中的 .subscribe(); this.httpService.getDataFromTheServer().subscribe((data) => {...});
-
这在the docs中有详细的介绍
标签: javascript angular typescript rxjs angular-services