在 angular 中实现可观察对象订阅的最佳位置
Best place to implement the subscribe of an observable in angular
我正在前端使用 angular 开发应用程序,我正在使用 http 客户端调用其余服务,我想知道实现 [=13= 订阅的最佳位置在哪里]() 可在服务或 component.ts?
中观察到
推荐的方法是完全不订阅。
1) 在服务中创建一个方法,returns observable
getAll(): Observable<MyData[]> {
return this.http<MyData[]>.get(PATH_TO_GET_ALL_ENDPOINT);
}
2) 在组件中调用此方法并存储 Observable
allData$: Observable<MyData[]> = this.myService.getAll();
3) 在模板中使用异步管道到 "Subscribe"
<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>
假设您有一项服务包含调用 api 的逻辑。
在您的服务文件中
Abc(): Observable<any>{ // 'any' to be replaced by type
return this.httpClient.get(url);
}
在你的组件文件中
this.Service.Abc().subscribe(
(res) => {
console.log(res);
}
)
我正在前端使用 angular 开发应用程序,我正在使用 http 客户端调用其余服务,我想知道实现 [=13= 订阅的最佳位置在哪里]() 可在服务或 component.ts?
中观察到推荐的方法是完全不订阅。
1) 在服务中创建一个方法,returns observable
getAll(): Observable<MyData[]> {
return this.http<MyData[]>.get(PATH_TO_GET_ALL_ENDPOINT);
}
2) 在组件中调用此方法并存储 Observable
allData$: Observable<MyData[]> = this.myService.getAll();
3) 在模板中使用异步管道到 "Subscribe"
<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>
假设您有一项服务包含调用 api 的逻辑。 在您的服务文件中
Abc(): Observable<any>{ // 'any' to be replaced by type
return this.httpClient.get(url);
}
在你的组件文件中
this.Service.Abc().subscribe(
(res) => {
console.log(res);
}
)