如何自动更新自定义指令?

当我以用户(例如admin)身份登录时,直到重新加载所登陆的页面,我才能看到新组件(“管理”按钮)。

authservice.service.ts(管理登录/注销)

import { Injectable } from '@angular/core';
import {environment as env } from './../../environments/environment';
import { HttpParams,HttpClient,HttpHeaders } from '@angular/common/http';
import { Auth } from '../core/model/auth';
import { Router } from '@angular/router';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { PermissionmanagerService } from './permissionmanager.service';
import { IsGrantedDirective } from '../features/permissions/isgranted.directive';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  data: Auth;
  error: any;
  constructor(private http: HttpClient,private router: Router) {
    this.setSession();
  }




  loginBasic(user: string,pwd: string): Observable<Auth> {
    this.error = null;
    // const fd = new FormData();
    // fd.append('utente',user);
    // fd.append('pwd',pwd);
    const params = new HttpParams()
      .set('utente',user)
      .set('pwd',pwd);
    const headers = new HttpHeaders()
      .set('Content-type','application/x-www-form-urlencoded')
      .set('authorization','Basic ' + btoa(user + ':' + pwd) );
    return this.http.post<Auth>(
      env.url + '/login',params,{
        headers,withCredentials: true
      }
      )
       .pipe(
         map(risp => {
           console.log(risp);
           /*
           const utente: Auth = new Auth();
           utente.username = risp.username;
           utente.expireSession = risp.expireSession;
           // utente.basicAuth = 'Basic ' + btoa(user + ':' + pwd);
           utente.nome = risp.nome
           utente.role = risp.role;
           */
          // risp è già di tipo Auth automaticamente
           localStorage.setItem('nxtLogged',JSON.stringify(risp));
           this.data = risp;
           //this.permission.authAs(risp.role);

           // console.log('utente salvato',utente);
           delete risp.token;
           return risp;
         })
       );
  }

  login(user: string,pwd: string): Observable<Auth> {
    this.error = null;
    return this.http.post<Auth>(
      env.url + '/authenticate',{utente: user,pwd}
      )
       .pipe(
         map(risp => {
           localStorage.setItem('nxtLogged',JSON.stringify(risp));


           this.data = risp;
           //this.permission.authAs(risp.role);

           delete risp.token;
           return risp;
         })
       );
  }

  logout() {
    this.destroySession()
    .subscribe(
      ok => {
        console.log('logout ok',ok);
        this.cleanLocalData();
        this.router.navigateByUrl('login');
      },err1 => {
        console.error('errore di logout',err1);
        this.cleanLocalData();
        this.router.navigateByUrl('login');
      }
    );
  }

  setSession() {
    if (localStorage.getItem('nxtLogged') != null) {
      this.data = JSON.parse(localStorage.getItem('nxtLogged'));
    }
  }


  destroySession() {
    return this.http.get(env.url + '/logout');
  }

  cleanLocalData() {
    this.data = null;
    localStorage.removeItem('nxtLogged');
  }

  getauth() {
    if (this.isLogged()) {
      const tmp: Auth = JSON.parse(localStorage.getItem('nxtLogged'));
      // return tmp.basicAuth;
      return tmp.token;
    }
  }



  getRoleAuth() {
    if (this.isLogged()) {
      const tmp: Auth = JSON.parse(localStorage.getItem('nxtLogged'));
      // return tmp.basicAuth;
      return tmp.role;
    }
  }



  isLogged() {
      let isAuth = this.data && this.data != null ? true : false;
      if (isAuth) {
        // controllo che non sia scaduto
        if (new Date().getTime() > this.data.expireSession) {
          isAuth = false;
          this.cleanLocalData();
        }
      }
      return isAuth;
  }


}

permissionmanager.service.ts(管理权限):该类具有用户角色,并控制该角色中的哪些权限。

import { Injectable } from '@angular/core';
import { PermissionBase } from '../features/permissions/PermissionBase';
import { PermissionType } from '../features/permissions/PermissionType';
import { PermissionsFactory } from '../features/permissions/permissionfactory';
import { AuthService } from './auth.service';

@Injectable({
  providedIn: 'root'
})
export class PermissionmanagerService {
  private permissions: PermissionBase;  //autorizzazioni
  constructor(private authService: AuthService) { 

    }

  isGranted(permission: PermissionType) {
    console.log('1');
    let authRole = this.authService.getRoleAuth();
    let permissions = PermissionsFactory.getInstance(authRole).permissionsss;

      for (let perm of permissions) {
        if (perm === permission){
          return true;

        }

    }
    return false;
  }
  authAs() {
    let authRole = this.authService.getRoleAuth();    
    console.log('2');
    this.permissions = PermissionsFactory.getInstance(authRole);


  }
}

我的指令

import { Directive,Input,TemplateRef,ViewContainerRef,Output,ElementRef,EventEmitter,HostListener,OnInit,OnDestroy  } from '@angular/core';
import { PermissionmanagerService } from 'src/app/services/permissionmanager.service';
import { PermissionType } from './PermissionType';
import { AuthService } from 'src/app/services/auth.service';
import { Auth } from 'src/app/core/model/auth';



@Directive({
  selector: '[appIsGranted]'
})
export class IsGrantedDirective implements OnInit {
  constructor(
    private templateRef: TemplateRef<any>,private viewContainer: ViewContainerRef,private permissionmanagerS: PermissionmanagerService,private authService: AuthService,private auth : Auth
  ) { }



  @Input() set appIsGranted(permission: PermissionType) {
    if(permission)
      this.isGranted(permission);
  }



  private isGranted(permission: PermissionType) {
    if (this.permissionmanagerS.isGranted(permission)) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainer.clear();
    }
  }

}
bmlun 回答:如何自动更新自定义指令?

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3013966.html

大家都在问