angular - 如何自动更新自定义指令?
问题描述
当我使用用户(例如管理员)登录时,我无法看到新组件(管理员按钮),直到我重新加载我登陆的页面。
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(manages the permissions):这个类接受角色用户并控制该角色中的权限。
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();
}
}
}
解决方案
推荐阅读
- flutter - Flutter 中的 PageView.Builder 在 null 上调用了 getter 'length'。接收方:null 尝试调用:长度
- firebase-realtime-database - Firebase 实时规则:使用基于角色(令牌)的身份验证将用户分成多个组
- c++ - C ++如何从构造函数中的数组参数初始化/复制const数组成员
- python - 查找下一个非 NaN 值的时间戳
- sql - 在oracle中将数据列成行
- sql-server - 如何在 SQL 中将字符串拆分为列表进行过滤?
- javascript - 如何在 Mongoose 中创建多个对象数组?
- r - 在 R 中预测多变量线性模型
- android - Recyclerview 按字母顺序排列的标题
- java - 如何在 Java 中迭代 Xml 文件并从中创建对象