【发布时间】:2018-10-03 12:04:48
【问题描述】:
我正在尝试将组件订阅到服务主题,以确保组件订阅在服务发射时运行。
问题是订阅只有第一次命中,之后订阅也没有命中第二次附加的可观察返回 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 时
【问题讨论】:
-
考虑使用
new ReplaySubject<Array<KeyValue<string>>>(1)保留最后一个值,直到loadStores()提供next值。这样,新订阅者将始终获得价值。 -
你不会在任何地方破坏组件和服务吧?
-
你能在stackbiz提供代码吗
-
@PranayRana 是的,我也没有破坏组件和服务。组件位于应用程序的 Header 部分,它会一直留在那里。
-
你在哪里打电话给
loadStores?
标签: angular typescript rxjs observable