67

I'm trying to get the updated value from a service variable (isSidebarVisible) which is keeps on updated by another component (header) with a click event (toggleSidebar).

sidebar.service.ts

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

@Injectable() 
export class SidebarService {
    isSidebarVisible: boolean;

    sidebarVisibilityChange: Subject<boolean> = new Subject<boolean>();

    constructor()  {
        this.isSidebarVisible = false;
    }

    toggleSidebarVisibilty() {
        this.isSidebarVisible = !this.isSidebarVisible
        this.sidebarVisibilityChange.next(this.isSidebarVisible);
    }
}

sidebar.component.ts

export class SidebarComponent implements OnInit {
    asideVisible: boolean;
    _asideSubscription: any;

    constructor(private sidebarService: SidebarService) {
        this.asideVisible = sidebarService.isSidebarVisible
        this._asideSubscription = sidebarService.sidebarVisibilityChange.subscribe((value) => {
            this.asideVisible = value
        })
    }
    
    ngOnInit() {
    }
}

header.component.ts (Where service variable is updated)

export class HeaderComponent implements OnInit {
    isSidebarVisible: boolean;
    _subscription: any;

    constructor(private sidebarService: SidebarService) {
        this._subscription = sidebarService.sidebarVisibilityChange.subscribe((value) => {
            this.isSidebarVisible = value
        })
    }

    toggleSidebar() {
        this.sidebarService.toggleSidebarVisibilty()
    }

    ngOnInit() {

    }
}

I can see the service variable value change in header.component.html when {{ isSidebarVisible }} but In sidebar.component.html it always prints the default value and never listened to the changes.

Please help me fix this.

FireStormHR
  • 27
  • 1
  • 9
Body
  • 3,156
  • 8
  • 35
  • 47

2 Answers2

99

Move subscription to the service, and both components can access this value. If you need value only once, you can use it directly (like I did in sidebar.component); If you need to update something with this value it you can use getter (example in header.component).

sidebar.service.ts:

@Injectable() 
export class SidebarService {
    isSidebarVisible: boolean;

    sidebarVisibilityChange: Subject<boolean> = new Subject<boolean>();

    constructor()  {
        this.sidebarVisibilityChange.subscribe((value) => {
            this.isSidebarVisible = value
        });
    }

    toggleSidebarVisibility() {
        this.sidebarVisibilityChange.next(!this.isSidebarVisible);
    }
}

sidebar.component.ts

export class SidebarComponent {
    asideVisible: boolean;

    constructor(private sidebarService: SidebarService) {
        this.asideVisible = sidebarService.isSidebarVisible;
    }
}

header.component.ts

export class HeaderComponent {
    constructor(private sidebarService: SidebarService) { }

    get isSidebarVisible(): boolean {
        return this.sidebarService.isSidebarVisible;
    }

    toggleSidebar() {
        this.sidebarService.toggleSidebarVisibility()
    }
}

You can also subscribe to the subject in either/both components and get the value there:

this.sidebarService.sidebarVisibilityChange.subscribe(value => {...});

If you want to know more about Subjects take a look here.

isherwood
  • 46,000
  • 15
  • 100
  • 132
Sasxa
  • 36,894
  • 14
  • 85
  • 98
  • Thank you! If I wanna print the return value of isSidebarVisible() in header.component, how do I do that? – Body Apr 01 '17 at 20:43
  • 1
    `

    {{ isSidebarVisible | json }}

    ` (:
    – Sasxa Apr 01 '17 at 20:44
  • Thank you! This is really helpful. – Zhang Buzz Jun 05 '18 at 16:43
  • 1
    I spent a ton of time on my project using this as a reference. I understood how it should work, but it just wasn't. The piece of information I was missing was about hierarchical injection. Once I understood that my new global-level Service needed to be referenced in the providers in the app.module (and not in the sub-components) so the information could be inherited down the tree, everything worked perfectly. – St.G Mar 11 '19 at 20:52
  • 1
    How does the subscriber get destroyed? Who does it? – ATL_DEV Nov 26 '19 at 18:03
  • I've followed this answer and implemented the same, however, I don't see the changes on my component. Only difference is that I'm not assigning the value that is intended for change in the constructor, but in a different function call. – Ajay Srikanth May 04 '20 at 07:15
2

@isherwood put me on the track, thanks! This was the question and answer that looked the most like my situation.

In my case, I have an app-wide userService that listens to changes in AngularFireAuth (authState) and when a valid user exists, it sets up a listener to that user's AngularFirestore document, containing the user's info like name, email, color, whatever (/appusers/${user.id}). All the pages that need anything from userService get those data live, since it's a listener ( .subscribe() )

My problem was that pages relying on the user document being ready (logged in and user document fetched) before going on to do more database stuff. When navigating straight to an internal page via deep links, the page would try to do database things before the user doc was ready, leading to error/crash.

Following @isherwoods instructions above, this is how I make sure my app's pages wait for the user data to be ready before trying to do additional database things with it:

user.service.ts

export class UserService {

userDocumentReady: boolean = false; // initial value is "userdoc is not ready"
userDocObserver: Subject<boolean> = new Subject<boolean>(); // observing that bool

constructor(
  public fireauth: AngularFireAuth,
  public afs: AngularFirestore,
) {

// watch variable
this.userDocObserver.subscribe(value => this.userDocumentReady = value);

this.fireauth.authState
  .subscribe(user => {
    if (user) {

      this.afs.doc(`/tooluser/${user.uid}`).snapshotChanges()
      .subscribe(usr => {
        if (usr.payload.data()) {
          console.log(`got user object from database:`, usr.payload.data());              
          this.currentUser = usr.payload.data();

          this.userDocObserver.next(true); // flip UserDocumentReady flag

mytools.page.ts

// this is a logged-in page of the app,
// accessible through deep link https://my.app.domain/mytools

export class UsersPage implements OnInit {

constructor(
  public userService: UserService,
) { }

ngOnInit() {
  if (this.userService.userDocumentReady) {
    console.log(`users: userdoc already here, no need to wait`);
    this.setupPageData();
    return;
  }

  // wait for userdoc before setting up page
  this.userService.userDocObserver.subscribe(docReady => {
    if (docReady){
      console.log(`mytools: user ready value ${docReady}. now setup page.`);
      this.setupPageData(); // this function does the database stuff that depends on the user data to be ready first
    }
  });
}

This "worksforme" now and behavior seems consistent. Also very handy when developing, as typing a URL in the browser bar causes this kind of direct navigation. Writing this to remember it - and who knows if it can be useful to others?

This is only my second ionic app, so if something is horribly wrong with my structuring/setup, I'm very much interested in comments on this solution :)

edit: added check in mytools.page.ts so that we won't wait (forever) on a new user doc if one already exists