Angular 2 - 变量更改时的更新视图

时间:2017-02-03 04:22:09

标签: html angular typescript

我的导航栏(app.component.html)上有一个按钮,我只想在用户登录时显示该按钮。 这是我目前的方法,由于后面解释的明显原因不起作用。我想知道如何修改它才能发挥作用。

在我的app.component.html中,我有以下按钮

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

在我的app.component.ts中,我试图将变量isCurrentUserExist绑定到一个函数,如果用户存在则返回true。 我相信这是问题,因为这段代码只在OnInit执行一次,反对以某种方式保持视图更新

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

供参考,在我的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
    }
}

关于我的应用程序的更多信息...... 在用户不存在时启动时,我有一个登录屏幕(登录组件)。 当用户登录时,它会进入firebase并获取用户信息(异步)并通过

将其存储到我的用户服务中
setCurrentUser(user: User)

所以在这一点上,我想更新导航栏中的按钮(存在于app.component.html中)并显示按钮。

我能做些什么来实现这个目标?

2 个答案:

答案 0 :(得分:4)

让我们试试这个: 使用BehaviorSubject

<强> UserService.ts

tsconfig

<强> app.component.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
    }
}

答案 1 :(得分:1)

app.component.ts

您将从函数中分配一次值。所以它永远不会改变。要解决此问题并实时更新,请使用boolean变量this.isCurrentUserExist = this.userService.isCurrentUserExist;的赋值函数实例。并在视图中将更改*ngIf表达式更改为函数isCurrentUserExist()

相关问题