【问题标题】:Angular 5 - Manage right the server requestAngular 5 - 管理服务器请求
【发布时间】: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


【解决方案1】:

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

//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())
     }

此解决方案还使您能够取消订阅 Observale

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

最后,您实际上并不需要将您的服务方法绑定到任何变量。你可以这样做:

//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())
   }

// 回答编辑

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

这样做:

// 组件.html

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

// 组件.ts

public items;

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

// service.ts

getDataFromTheServer(){
   return this.http.post(url).pipe(map(res => res.json());
}

【讨论】:

  • 感谢您的快速回复。请看我的编辑
  • 非常有趣。为什么不推荐呢?
【解决方案2】:

你可以这样做:

//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&lt;any&gt;,您需要订阅它。

【讨论】:

  • 感谢您的快速回复。请看我的编辑
猜你喜欢
  • 2018-12-23
  • 1970-01-01
  • 2013-05-14
  • 1970-01-01
  • 2016-04-05
  • 2019-11-01
  • 2017-03-07
  • 2018-02-15
  • 2015-11-11
相关资源
最近更新 更多