【问题标题】:How to I get directive to run again on data load如何让指令在数据加载时再次运行
【发布时间】:2018-07-28 22:35:09
【问题描述】:

我有一个指令应该检查用户是否有声明,然后基于此显示相应的菜单元素。

  export class ClaimsDirective {

  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef,
    private authorizationService: AuthorizationService
  ) { }

  @Input() set claims(allowedClaims: Array<string>) {
      let shouldShow: boolean = false;
      for (let allowedClaim of allowedClaims) {
        if (this.authorizationService.hasClaim(allowedClaim))
          shouldShow = true;
      }
      if (shouldShow) {
        this.viewContainer.createEmbeddedView(this.templateRef);
      } else {
        this.viewContainer.clear();
      }
    }
}

这在重新加载时工作得很好。但是,如果我退出,它就不会运行。让这个在登录/退出时重新检查的最佳方法是什么?

编辑:基于 cmets 和一些阅读:

在授权服务中,我创建了一个 BehaviorSubject

  private isAuth: BehaviorSubject<boolean>;
  public getIsAuth(): Observable<boolean> {
    return this.isAuth.asObservable();
  }

然后在构造函数中检查你是否登录:

const currentUser = JSON.parse(localStorage.getItem(this.currentUserKey));
if (currentUser)
  this.isAuth = new BehaviorSubject<boolean>(true);
else
  this.isAuth = new BehaviorSubject<boolean>(false);

然后在登录/注销时:

this.isAuth.next(true);

最后在我订阅的指令中:

this.authorizationService.getIsAuth().subscribe(v=> this.checkShouldShow());

这是 Angular 5 /RxJS 的正确模式吗?

(这是基于这里的答案:https://www.reddit.com/r/Angular2/comments/76inse/noob_observable_on_change_of_value/)

【问题讨论】:

  • authorizationService 应该公开一个 observable 以监视当前的身份验证状态。
  • 我不知道你说的那句话是什么意思,可以举个例子吗?
  • 应该有类似 isAuth$ 的 observable 可以被依赖于身份验证状态变化的单元订阅(例如这个指令)。它应该如何完成完全取决于服务的工作方式。
  • 通过编辑添加了解决方案,对吗?
  • Yes' 这就是通常的做法。 getIsAuth 没有理由成为一个函数,它只是isAuth$ = this.isAuth.asObservable()。请注意,由于 isAuth 是行为主体,因此当前值也可以作为 isAuth.value 使用,以备不时之需。

标签: angular angular5


【解决方案1】:

为了让其他单位在 auth 状态发生变化时得到通知,auth 服务应该公开一个可以订阅的 observable:

private isAuth = new BehaviorSubject<boolean>(false);
public isAuth$ = this.isAuth.asObservable();

它可以使用this.isAuth.next(...) 发出状态更改。由于isAuth 是BehaviorSubject,因此当前值也可以作为this.isAuth.value 使用。

其他单位可以通过以下方式订阅更改:

authorizationService.isAuth$.subscribe(isAuth => { ... });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    • 2023-03-23
    • 2015-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多