user172902
user172902

Reputation: 3581

Angular 2 - Update view when variable changes

I have a button on my nav bar (app.component.html) that I want to only show when the user is logged in. This is my current approach that does not work for obvious reasons explained later. I want to find out how I can modify it to work.

Inside my app.component.html, I have the following button

<button *ngIf="isCurrentUserExist">MyButton</button>

Inside my app.component.ts, I am trying to bound the variable isCurrentUserExist to a function that returns true if the user exists. I believe this is the problem because this code is only executed once at OnInit as oppose to somehow keeping the view updated

ngOnInit() {
  this.isCurrentUserExist = this.userService.isCurrentUserExist();    
}

For reference, inside my UserService.ts

export class UserService {

    private currentUser: User

    constructor(private http: Http,private angularFire: AngularFire) { }

    getCurrentUser(): User {
        return this.currentUser
    }

    setCurrentUser(user: User) {
        this.currentUser = user;
    }

    isCurrentUserExist(): boolean {
        if (this.currentUser) {
        return true
        }
        return false
    }
}

A bit more information about my app... Upon start up when the user does not exist, I have a login screen (login component). When the user logs in, it goes to firebase and grab the user information (async) and store it to my user service via

setCurrentUser(user: User)

So at this point, I like to update the button in my nav bar (which exists in app.component.html) and show the button.

What can I do to achieve this?

Upvotes: 4

Views: 7065

Answers (2)

Tiep Phan
Tiep Phan

Reputation: 12596

let's try this: using BehaviorSubject

UserService.ts

import { Subject, BehaviorSubject} from 'rxjs';

export class UserService {

    private currentUser: User;
    public loggedIn: Subject = new BehaviorSubject<boolean>(false);

    constructor(private http: Http,private angularFire: AngularFire) { }

    getCurrentUser(): User {
        return this.currentUser
    }

    setCurrentUser(user: User) { // this method must call when async process - grab firebase info - finished
        this.currentUser = user;
        this.loggedIn.next(true);
    }

    isCurrentUserExist(): boolean {
        if (this.currentUser) {
        return true
        }
        return false
    }
}

app.component.ts

ngOnInit() {
  this.userService.loggedIn.subscribe(response => this.isCurrentUserExist = response);    
}

Upvotes: 6

Kishan Mundha
Kishan Mundha

Reputation: 3141

in app.component.ts you are assigned value from function once. So it will never change. To resolve this problem and to real time update use assign function instance of boolean variable this.isCurrentUserExist = this.userService.isCurrentUserExist;. And in view change change *ngIf expression as function isCurrentUserExist().

Upvotes: 1

Related Questions