簡體   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