【问题标题】:Angular 2 - Update view when variable changesAngular 2 - 变量更改时更新视图
【发布时间】:2018-05-26 08:28:42
【问题描述】:

我的导航栏 (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 中)并显示该按钮。

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

【问题讨论】:

    标签: html angular typescript


    【解决方案1】:

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

    【讨论】:

    • 嗨,领带。谢谢你。它工作得很好。我之前一直在考虑事件发射器。但是,除非我绝望,否则我不喜欢使用它,因为感觉就像信号在空中飞行,等待有人抓住它(有点像推送通知)。这个 BehaviorSubject 也感觉像是某种事件发射器?你知道是否有另一种方法(用于学习目的)
    • 您可以创建自定义事件发射器系统(可能基于 observable),然后在某个地方,您可以订阅某种事件,例如“user.login”(Ionic 2 有自己的事件系统)。每当事件触发时,您将获得价值 - 有效负载 - 做任何您喜欢的事情。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2018-11-25
      • 2017-05-18
      • 1970-01-01
      • 1970-01-01
      • 2017-04-07
      • 2019-02-28
      • 1970-01-01
      • 2016-08-23
      • 2017-09-07
      相关资源
      最近更新 更多