【问题标题】:Best place to implement the subscribe of an observable in angular [closed]以角度实现订阅的最佳位置[关闭]
【发布时间】:2020-03-31 07:18:15
【问题描述】:

我正在前端使用 Angular 开发一个应用程序,我正在使用 http 客户端调用 rest 服务,我想知道在哪里实现订阅 httpClient.get() 的 observable 的最佳位置服务还是在component.ts中?

【问题讨论】:

标签: javascript angular typescript angular7 angular8


【解决方案1】:

假设您有一个服务,其中包含调用 api 的逻辑。 在您的服务文件中

Abc(): Observable<any>{ // 'any' to be replaced by type
  return this.httpClient.get(url);
}

在你的组件文件中

    this.Service.Abc().subscribe(
    (res) => {
        console.log(res);
    }
)

【讨论】:

    【解决方案2】:

    推荐的方法是根本不订阅。

    1) 在服务中创建一个返回可观察对象的方法

    getAll(): Observable<MyData[]> {
      return this.http<MyData[]>.get(PATH_TO_GET_ALL_ENDPOINT);
    }
    

    2) 在组件中调用该方法并存储 Observable

    allData$: Observable<MyData[]> = this.myService.getAll();
    

    3) 在模板中使用异步管道“订阅”

    <ng-container *ngIf="allData$ | async as allData; else pending">
      <div *ngFor="let data of allData">{{ data | json }}</div>
    </ng-container>
    <ng-template #pending>pending...</ng-template>
    

    【讨论】:

      猜你喜欢
      • 2012-10-07
      • 2018-04-19
      • 1970-01-01
      • 2023-04-08
      • 2012-02-22
      • 2020-11-18
      • 2021-01-20
      • 2021-09-22
      • 1970-01-01
      相关资源
      最近更新 更多