繁体   English   中英

Angular 组件在值更改时未更新

[英]Angular component not updating when value changed

当我的一个变量发生变化时,我在更新ngIf时遇到了一些麻烦。

我有一个具有用户身份验证的离子(角度)应用程序。 当应用程序加载时,它应该隐藏导航菜单并在用户退出时仅显示登录视图。 当用户登录时,应用程序应在从服务器检索用户数据时显示加载屏幕,然后显示适当的视图并显示导航菜单。 我无法显示导航菜单。 我认为这与更改isLoggedIn在视图完成渲染后运行的代码有关,但我不确定,因为任何强制重新渲染的尝试都没有产生任何变化

export class AppComponent {

    public user: User
    public isLoggedIn = false;
    
  public appPages = [
    { title: 'Home', url: '/assignment', icon: 'home', role: 'Employee'},
    { title: 'Home', url: '/supervisor', icon: 'home', role: 'Supervisor'},
    { title: 'Assignments', url: '/assign', icon: 'body', role: 'Supervisor'},
    { title: 'Manager', url: '/manager', icon: 'briefcase', role: 'Supervisor'},
    { title: 'Settings', url: '/settings', icon: 'settings', role: 'any'}
  ];
  constructor(private router: Router, private auth: Auth, private userService: UserService) {
    this.router.navigate(["/loader"]);
    this.authorise();
  }
  
  authorise(){
      if(localStorage.getItem("uid")){
        console.log("user Is Logged In: Getting data");
        this.userService.getUser(localStorage.getItem("uid")).subscribe(res => {
            console.log("assigning user")
            console.log(res);
            this.user = res
            this.checkRole();   
        });
    }else{
        this.router.navigate(["/login"])
    }

  }
  
  checkRole(){
  console.log("checking....");
    if(this.user.role == "Employee"){
         this.isLoggedIn = true;
        this.router.navigate(["/assignment"]);
    }else{
        this.isLoggedIn = true;
        this.router.navigate(["/supervisor"]);  
    }
  }

}```

我的模板文件(只是相关部分)

<ion-app>
  <ion-split-pane contentId="main-content">
    <ion-menu contentId="main-content" type="overlay" *ngIf="isLoggedIn">
      <ion-content>
        <ion-list id="menu-list">
        ..........

如您所见,当应用程序加载时, isLoggedIn为 false,从而强制不呈现ion-menu

然后脚本构造函数调用授权并从 Firestore 数据库异步检索用户的文件。 一旦检索到该数据,它就会调用checkRole并在router-outlet中加载适当的页面(未包含在此示例中)。 建立用户角色后, checkRole集的isLoggedintrue ,这是我希望模板开始显示菜单栏的位置。

有谁知道如何做到这一点?

谢谢:)

做类似的事情:

import { MenuController } from '@ionic/angular'; // import menu controller


constructor(private menu: MenuController) { 
  this.menu.enable(false); // make your menu hidden by default.
}

// inside your checkRole Function enable your menu.
checkRole(){
    if(this.user.role == "Employee"){
      //this.isLoggedIn = true;
      this.menu.enable(true);
      this.router.navigate(["/assignment"]);
    }else{
      //this.isLoggedIn = true;
      this.menu.enable(true);
      this.router.navigate(["/supervisor"]);  
    }
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM