How to implement behavior subject using service in Angular 8

I’m going to show you a simple way:

@Injectable() 
export class ProfileService {

    private profileObs$: BehaviorSubject<Profile> = new BehaviorSubject(null);

    getProfileObs(): Observable<Profile> {
        return this.profileObs$.asObservable();
    }

    setProfileObs(profile: Profile) {
        this.profileObs$.next(profile);
    }
}

Now when you update something anywhere in the application, you can set that change by the ProfileService and each subscriber is receiving the change. I recommend you subscribe in ngOnInit.

ngOnInit() {
  this.profileService.getProfileObs().subscribe(profile => this.profile = profile);
}

Never forget to unsubscribe from the observables to prevent memory leaks!

There are many ways u can do that –> Use a subscription and unsubscribe in ngOnDestroy() or use another subject and deliver it to takeUntil like this:

unsubscribe$: Subject<boolean> = new Subject();

...

ngOnInit() {    
  this.profileService.getProfileObs()
                     .pipe(takeUntil(this.unsubscribe$))
                     .subscribe(profile => this.profile = profile);
}

ngOnDestroy() {
  this.unsubscribe$.next(true);
  this.unsubscribe$.complete();
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)