小编Geo*_*ida的帖子

rxjs observable.pipe(take(1)) 与 toPromise

最近我被转移到一个新项目,该项目使用 angular 6 作为前端框架和 REST 服务的 spring。

该项目已经开发了 2 年,我观察到几乎所有使用 angular HttpClient 发出的 HTTP 请求都通过管道从 rxjs 中获取过滤器。所有 REST API 只发出一个值。不需要手动取消和 observable 的惰性属性。

我的直觉是使用 toPromise() 将是更好的编码方式。

你怎么看?

  //customer-service.ts
  constructor(private http: HttpClient) {

  }

  public getCustomers() {
     return http.get('/customers');
  }

  //component.ts
  public ngOnInit() {
      this.customerService.getCustomers().pipe(take(1)).subscribe((customers) => {
           //do some stuff
      })
  }
Run Code Online (Sandbox Code Playgroud)

我建议的方法:

  //customer-service.ts
  constructor(private http: HttpClient) {

  }

  public getCustomers() : Promise<Array<Customer>> {
     return http.get('/customers').toPromise();
  }

  //component.ts
  public ngOnInit() {
      this.customerService.getCustomers().then((customers: Array<Customer>) => {
         //do some stuff
      })
  }
Run Code Online (Sandbox Code Playgroud)

我认为我的方法更好,因为它是强类型的并且更干净。

javascript observable rxjs typescript angular

5
推荐指数
2
解决办法
2784
查看次数

标签 统计

angular ×1

javascript ×1

observable ×1

rxjs ×1

typescript ×1