Angular 5-管理正确的服务器请求

时间:2019-01-31 11:30:03

标签: javascript angular typescript rxjs angular-services

我了解到,建议通过服务(而不是组件)发出服务器请求,以便该功能的请求可以被其他组件重用。最终,我们需要组件中的服务器响应。

我的问题是从组件到服务的调用以获取数据的最佳实践是什么。我问,因为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()

还是还有另一种清洁组件的方法?还是我对“通过服务发出服务器请求”的建议不够理解? 我很乐意更清楚地解释。

2 个答案:

答案 0 :(得分:1)

Ofc您的第一个解决方案将无法使用。这是因为“ this.http.post”方法不是返回请求数据,而是可观察的对象。因此,您需要做的就是订阅您的对象:)

-stream_loop

此解决方案还使您能够退订观测站

//data.component.ts
const data = this.httpService.getDataFromTheServer();
data.subscribe(res => console.log(res)); // or just bind res to any other variable

//httpService.service.ts
  getDataFromTheServer(){
     return this.http.post(url).map(
       res=>res.json())
     }

最后,您实际上不需要将服务方法绑定到任何变量。您可以简单地做到这一点:

ngOnDestroy() {
  this.data.unsubscribe();
}

//修改答案

理论上您可以,但是我不会推荐它。如果要保持组件清晰,只需使用异步管道

这样做:

// component.html

//data.component.ts
ngOnInit() {
  this.httpService.getDataFromTheServer()
  .subscribe(res => myVariable = res) // binding response from server to variable
}

//httpService.service.ts
  getDataFromTheServer(){
     return this.http.post(url)
     .map(res=>res.json())
   }

// component.ts

<ul>
  <li *ngFor="let item of (items | async)">
</ul>
// or if its not an array
<h1>{{ item | async }}</h1>

// service.ts

public items;

ngOnInit() {
  this.items = this.httpService.getDataFromTheServer();
}

答案 1 :(得分:0)

您可以执行以下操作:

//data.component.ts
this.httpService.getDataFromTheServer().subscribe((data) => {
   //assign your data here
});

//httpService.service.ts
getDataFromTheServer(){
   return this.http.post(url);
}

this.http.post返回Observable<any>时,您需要订阅它。