Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Service Observable doesnt trigger components subscription second time

I am trying to subscribe component to Service Subject to make sure the component subscription run on service emittion.

The problem is subscription hits only first time after that the subscription doesnt hit also the observable return 0 subscription attached second time.

Following is the code:

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

While the component is.

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

Aim to call that the above subscription in component every time

When Store Service - loadStores is called

like image 270
Shan Khan Avatar asked Apr 23 '18 12:04

Shan Khan


1 Answers

You are applying an antipattern: NEVER subscribe a service call in the same service. You have to return the call and the component have to subscribe to this Observable.

Any way, since the storeList is a subject, you can simplify doing that:

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

because a subject is an observer aswell

like image 190
Sergi Dote Teixidor Avatar answered Sep 30 '22 19:09

Sergi Dote Teixidor