Angular Service Observable第二次不会触发组件订阅

前端之家收集整理的这篇文章主要介绍了Angular Service Observable第二次不会触发组件订阅前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试订阅服务主题的组件,以确保组件订阅在服务发射上运行.

问题是订阅命中率仅在第一次订阅后也没有达到第二次附加的可观察返回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();
    } 
}

虽然组件是.

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

目的是每次都在组件中调用上面的订阅

调用Store Service – loadStores时

解决方法

您正在应用反模式:永远不会在同一服务中订阅服务调用.您必须返回调用,组件必须订阅此Observable.

无论如何,由于storeList是一个主题,你可以简化这样做:

this.getAllStores().subscribe(this.storesList);

因为一个主体也是一个观察者

猜你在找的Angularjs相关文章