use*_*902 4 html typescript angular
我的导航栏 (app.component.html) 上有一个按钮,我只想在用户登录时显示该按钮。这是我当前的方法,但由于稍后解释的明显原因而不起作用。我想知道如何修改它才能工作。
在我的 app.component.html 中,我有以下按钮
<button *ngIf="isCurrentUserExist">MyButton</button>
Run Code Online (Sandbox Code Playgroud)
在我的 app.component.ts 中,我尝试将变量 isCurrentUserExist 绑定到一个函数,如果用户存在则返回 true。我相信这就是问题所在,因为此代码仅在 OnInit 处执行一次,而不是以某种方式保持视图更新
ngOnInit() {
this.isCurrentUserExist = this.userService.isCurrentUserExist();
}
Run Code Online (Sandbox Code Playgroud)
作为参考,在我的 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
}
}
Run Code Online (Sandbox Code Playgroud)
有关我的应用程序的更多信息...在用户不存在时启动时,我有一个登录屏幕(登录组件)。当用户登录时,它会转到 firebase 并获取用户信息(异步)并将其存储到我的用户服务中
setCurrentUser(user: User)
Run Code Online (Sandbox Code Playgroud)
因此,此时,我想更新导航栏中的按钮(存在于 app.component.html 中)并显示该按钮。
我可以做什么来实现这个目标?
让我们试试这个:使用BehaviorSubject
用户服务.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
}
}
Run Code Online (Sandbox Code Playgroud)
应用程序组件.ts
ngOnInit() {
this.userService.loggedIn.subscribe(response => this.isCurrentUserExist = response);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6908 次 |
| 最近记录: |