html - Angular 2 - 变量更改时更新 View

标签 html angular typescript

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

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

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

在我的 app.component.ts 中,我试图将变量 isCurrentUserExist 绑定(bind)到一个函数,该函数在用户存在时返回 true。 我相信这是问题所在,因为这段代码只在 OnInit 执行一次,而不是以某种方式保持 View 更新

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 中)并显示该按钮。

我该怎么做才能实现这一目标?

最佳答案

让我们试试这个: 使用 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);    
}

关于html - Angular 2 - 变量更改时更新 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42016736/

相关文章:

html - 居中包装 Div

javascript - 如何更改函数内部的值?

javascript - 将 typescript 函数保存为对象变量(Angular 6)

使用 ngFor 可观察 Angular

javascript - 甚至跨浏览器逐一执行测试

javascript - 查看/编辑 html 表单

html - 100% 宽度的 HTML 元素问题

angular - 如何获取 Angular 2 组件的 html 模板?

javascript - 使用扩展来更新对现有对象的引用?

javascript - TypeScript 和 React 之间有什么关系?