lintu
lintu

Reputation: 1102

Watch for changes in service and update component in angular2, typescript

I have a component and a service. I want to notify my component whenever a boolean property in my service changes. I think I should use Observable and Observer from rxjs.

I made the service and component which is not working as expected.

AppComponent.ts

import {  Component } from '@angular/core';
import { UserData } from 'user-data.service';
@Component({
    selector: 'app',
    templateUrl: '<div></div>'
})
export class AppComponent {
    isLoggedIn: boolean;
    constructor(public userData: UserData) {
       userData.isLoggedIn.subscribe(isLoggedIn => {
           this.isLoggedIn = isLoggedIn;
       });//???
    }
    ???
}

UserDataService.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable()
export class UserData {
    isLoggedIn: Observable<boolean>; // ???
    observer: Observer<boolean>; // ??? giving an error in tsc (Type 'Observer' is not generic)
    constructor() {
        this.isLoggedIn = new Observable(observer => 
           this.observer = observer
        ).share(); ///???
    }
    changeLoginStatus (isLoggedIn: boolean) { // function called from login/logout actions
        this.observer.next(isLoggedIn); // ??? not sure
    }

}

Upvotes: 1

Views: 5978

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657308

The easiest way is to use a BehaviorSubject with an initial value:

export class UserData {
  isLoggedIn: Subject<bool> = new BehaviorSubject(false);
  changeLoginStatus (isLoggedIn: boolean) { 
    this.isLoggedIn.next(isLoggedIn); // ??? not sure
  } 
}

See also https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

As @KonradGarus suggested, the Subject should be kept private.

export class UserData {
  private isLoggedIn: Subject<bool> = new BehaviorSubject(false);
  isLoggedIn$ = this.isLoggedIn.asObservable();
  changeLoginStatus (isLoggedIn: boolean) { 
    this.isLoggedIn.next(isLoggedIn); 
  } 
}

The cookbook linked above also contains a full example where the Subject is kept private.

Upvotes: 2

Related Questions