Sha*_*han 4 observable rxjs typescript angular
我正在尝试订阅服务主题的组件,以确保组件订阅在服务发射上运行.
问题是订阅命中率仅在第一次订阅后也没有达到第二次附加的可观察返回0订阅.
以下是代码:
export class StoreService {
private storesList : Subject<Array<KeyValue<string>>> = null;
constructor(private http: Http, private _uService: UserService) {
this.storesList = new Subject<Array<KeyValue<string>>>();
}
loadStores(): void{
this.getAllStores().subscribe(m=>{
debugger;
this.storesList.next(m);
});
}
storeListEvent(): Observable<Array<KeyValue<string>>>{
return this.storesList.asObservable();
}
}
Run Code Online (Sandbox Code Playgroud)
虽然组件是.
export class HeaderNavComponent implements OnInit, AfterViewInit,OnDestroy {
private storeUpdateSubscription = null;
constructor(private _userService: UserService, private cdRef: ChangeDetectorRef, private _storeService: StoreService, private router: Router, private location: Location) {
this.storeUpdateSubscription = this._storeService.storeListEvent().subscribe(stores => {
debugger;
this.appStore = stores;
this.verifySuperAdmin();
});
}
Run Code Online (Sandbox Code Playgroud)
目的是每次都在组件中调用上面的订阅
当loadStores调用商店服务时
小智 5
您正在应用反模式:永远不会在同一服务中订阅服务调用.您必须返回调用,组件必须订阅此Observable.
无论如何,由于storeList是一个主题,你可以简化这样做:
this.getAllStores().subscribe(this.storesList);
Run Code Online (Sandbox Code Playgroud)
因为一个主体也是一个观察者
| 归档时间: |
|
| 查看次数: |
1123 次 |
| 最近记录: |