重新加载 Angular 9 个组件元素数据更改

Reload Angular 9 component elements on data change

我正在使用 Angular 9,我想在用户登录时动态更改菜单项的数据。但是,由于菜单与主页一起加载,当用户登录时登录后,数据更改不会反映在菜单项中,直到我 手动刷新页面 。我尝试使用 Renderer 2、ChangeDetectorRef 和 ElementRef,但无法自动重新加载菜单。由于实际的组件代码很长,下面我只添加了相关元素。问我是否需要了解其他信息:

Html:

              <div class="widget-text">
                  <a mat-button [matMenuTriggerFor]="accountMenu" #accountMenuTrigger="matMenuTrigger" *ngIf="!isLoggedIn">
                    <mat-icon>person</mat-icon>
                    <span fxShow="false" fxShow.gt-sm class="flag-menu-title">Account</span>
                    <mat-icon class="mat-icon-sm caret cur-icon">arrow_drop_down</mat-icon>
                </a>
                <mat-menu #accountMenu="matMenu" [overlapTrigger]="false" xPosition="before" class="app-dropdown">
                    <span>
                        <button mat-menu-item [routerLink]="['/admin/login']" routerLinkActive="router-link-active">
                          <mat-icon >person</mat-icon>
                          <span>Login</span>
                        </button>
                        <button mat-menu-item [routerLink]="['/admin/login']" routerLinkActive="router-link-active">
                          <mat-icon>person_add</mat-icon>
                          <span>Register</span>
                        </button>
                    </span>
                </mat-menu>
                <a mat-button [matMenuTriggerFor]="profileMenu" #profileMenuTrigger="matMenuTrigger" *ngIf="isLoggedIn">
                  <mat-icon>person</mat-icon>
                  <span fxShow="false" fxShow.gt-sm class="flag-menu-title">Howdy, {{name}}</span>
                  <mat-icon class="mat-icon-sm caret cur-icon">arrow_drop_down</mat-icon>
              </a>
              <mat-menu #profileMenu="matMenu" [overlapTrigger]="false" xPosition="before" class="app-dropdown">
                  <span>
                      <button mat-menu-item [routerLink]="['/admin/profile']" routerLinkActive="router-link-active">
                        <mat-icon >person</mat-icon>
                        <span>Profile</span>
                      </button>
                      <button mat-menu-item (click)="logout()">
                        <mat-icon>warning</mat-icon>
                        <span>Logout</span>
                      </button>
                  </span>
              </mat-menu>
                  </div>

打字稿:

public name;
public isLoggedIn = false;

  constructor(public router: Router, private cartService: CartService, public sidenavMenuService:SidebarMenuService) {
    this.checkLogin();
    this.name = Cookie.get('userName');
  }

public checkLogin(): any {
    if(Cookie.get('authtoken')) {
      this.isLoggedIn = true;
    }
  }

构造函数在页面创建过程中只执行一次。

constructor(public router: Router, private cartService: CartService, public sidenavMenuService:SidebarMenuService) {
    this.checkLogin();
    this.name = Cookie.get('userName');
  }

现在,根据代码,如果在构造期间未找到 cookie authtoken,您的应用无法知道它是否由另一个(登录)进程创建。

您应该在完成登录后立即调用 checkLogin 函数和 name 赋值。

你不需要让事情变得复杂,当你登录你的登录守卫(即auth guard)时。

import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuardService implements CanActivate {
  
  constructor(public auth: AuthService, public router: Router , private sideMenuService: SideMenuService) {}
  
  canActivate(): boolean {
    if (!this.auth.isAuthenticated()) {
      this.sideMenuService.sideMenuData.next({...data});  // so here you can dispatch the side menu service data . 
      this.router.navigate(['dashboard']); // here after authentication it 
                                             will redirect to your dashboard 
                                             page
      return false;
     }
   return true;
   } 
 }
  
} 

因此,当您登陆仪表板页面时重定向后,在仪表板组件中,您还注入了 sideMenu 服务并订阅了 BehaviourSubject 菜单数据字段。

public name;
public isLoggedIn = false; // here you don't need to check login
                        // because you come here from auth guard
  constructor(public router: Router, private cartService: CartService, 
   public sidenavMenuService: SidebarMenuService) {
   this.checkLogin();  // same no need to check login in each 
                         component if you use auth guard 

   this.name = Cookie.get('userName');
}

public ngOnInit(){
  this.sideMenuService.sideMenuData.subscribe((data)=>{
    // hered you get the data dynamic , you can assign to any 
    // component field.
 });
}
 public checkLogin(): any {
    if(Cookie.get('authtoken')) {
    this.isLoggedIn = true;
 }

}

这就是每次您登录时发送一些动态数据时的方式,您的 behaviorSubject 将得到更新,并且您在 Dashboard 组件中订阅的任何地方都将获得动态数据。

希望对您有所帮助。