我正在尝试向Service Subject订阅组件,以确保组件订阅在服务发出时运行。

问题是订阅仅在第一次击中之后,订阅也没有击中,第二次也未击中可观察到的返回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);

因为主题也是观察者

关于Angular Service Observable不会第二次触发组件订阅,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49981153/

10-09 16:11