【问题标题】:Angular 2 structural directive with service call带有服务调用的 Angular 2 结构指令
【发布时间】:2017-09-27 18:15:06
【问题描述】:

我创建了一个结构指令来检查用户是否具有某些权限。权限是从后端获取并保存在服务本身中。结构指令根据 DI 注入服务,并应检查服务中是否存在权限。

想法:服务应该从后端获取所有权限 -> 通过指令检查权限 -> 如果为真则渲染

问题是服务没有获取服务。服务等待结构指令的所有查询,然后开始获取服务。

看起来像这样:

authority.directive.ts

@Directive({
  selector: '[authority]'
})

export class AuthorityDirective {
  constructor(private userService: UserService,
    private templateRef: TemplateRef < any > ,
    private viewContainer: ViewContainerRef) {}

  @Input() set bdAuthority(authName: string) {
    if (this.userService.hasAuthority(authName)) {
      this.viewContainer.createEmbeddedView(this.templateRef);
      return;
    }
    this.viewContainer.clear();
    return;

  }
}

authority.service.ts 像这样

    // check if the current user has the defined privilege
    public hasAuthority(authorityName: string): boolean {
      return (
        this.authorityCache
        .filter((authority) => {
          return authorityName === authority.name
        })
        .length) > 0;
    }

    public onBrowserReload(tempUser: User) {
      this.getUserById(tempUser.id).subscribe(user => {
        this.updatePrivilegesAndUser(user);
      });
    }
  }
}

有没有办法让服务早点启动?

【问题讨论】:

  • 仅供参考的结构指令旨在改变 DOM,如 *ngIf 和 *ngFor
  • 渲染顺序有区别吗?

标签: angular angular-directive


【解决方案1】:

根据最后的回复,我给自己分配了调查任务,并为类似问题提出了解决方案。

我必须从后端端点刷新权限数组,在结构指令中使用这个数组我确定用户是否可以看到该元素,我正在使用相同的代码接近解决方案,并且有相同的错误,对后端的权限数组调用没有足够快地刷新数组,因此解决方案是使用和 AsyncSubject。调用后,AsyncSubject 将解析为一个值,因此您可以从方法中返回它。

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, AsyncSubject } from 'rxjs';
import { Observable, of } from 'rxjs';

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

  baseUrl = '/apiURL/v5';
  permissionsSubject = new AsyncSubject;
  hasPermissions = false;
  constructor(private http: HttpClient) { }

  async updatePermissions(clientId, roleName) {
    const response = await this.http.get(this.getRoleUrl(clientId, roleName)).toPromise();
    this.permissionsSubject.next(response['permissions'] || []);
    this.permissionsSubject.complete(); // Once I finish sending the value that I need i end the subject to propagate its value to all the subscribers.
  }

  getRoleUrl(clientId, roleName) {
    return `${this.baseUrl}/client/${clientId}/roles/${roleName}`;
  }

  setCachedPermissions(permissions) {
    this.permissionsSubject.next(permissions);
  }

  getCachedPermissions() {
    return this.permissionsSubject.asObservable();
  }
   // This is the method used by the structural directive to determine if the object is rendered
  cacheHasPermission(slug) {
    return new Promise((resolve, reject) => {
      this.getCachedPermissions().subscribe((permissions: String[]) => {
        resolve(permissions.includes(slug));
      });
    });
  }
}

【讨论】:

    猜你喜欢
    • 2016-11-25
    • 2016-07-27
    • 1970-01-01
    • 2018-10-06
    • 2016-06-23
    • 1970-01-01
    • 2017-11-10
    • 2019-02-01
    • 1970-01-01
    相关资源
    最近更新 更多