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?
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);    
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With