Angular 直接使用方法时,指令结果不相同

Angular 直接使用方法时,指令结果不相同,angular,angular8,Angular,Angular8,在Angular 8组件HTML上,我通过authorize指令检查授权: <button (click)="createPost()" *authorize="'Create'; id: postId">Add post > Directive</button> <button (click)="createPost()" *ngIf="authorize('Create', postId)">Add post > Method in Com

在Angular 8组件HTML上,我通过
authorize
指令检查授权:

 <button (click)="createPost()" *authorize="'Create'; id: postId">Add post > Directive</button>
<button (click)="createPost()" *ngIf="authorize('Create', postId)">Add post > Method in Component</button>
在这种情况下,它工作良好。。。所以我认为我的指令有一些问题:

授权指令

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

export class AuthorizeDirective implements OnInit {

  requirement: Requirement;
  id: number;

  @Input() set authorize(requirement: string) {
    this.requirement = Requirement[requirement];
  }

  @Input() set authorizeId(id: number) {
    this.id = id;
  }

  constructor(private template: TemplateRef<any>, private container: ViewContainerRef, private authorizationService: AuthorizationService) { }

  ngOnInit() { 

    this.authorizationService.authorize(this.requirement, this.id).pipe(
      distinctUntilChanged()
    ).subscribe(x => {
      x ? this.container.createEmbeddedView(this.template) : this.container.clear();
    });

  }

}
@Injectable({ 
  providedIn: 'root' 
})

export class AuthorizationService {

  private notifier: Subscription;

  private permissions$: BehaviorSubject<PermissionModel[]> = new BehaviorSubject<PermissionModel[]>([]);

  constructor(private noteService: NoteService, private permissionService: PermissionService, private authenticationService: AuthenticationService) { 

    this.getPermissions();

    // Update permissions if user permissions were modified
    this.notifier = this.noteService.get().subscribe((note: Note) => { 

      if (note.code == NoteCode.PermissionsModified) {
        this.getPermissions();
      }

    });

  }

  private getPermissions() {

    let userId: this.authenticationService.getUserId();

    this.permissionService.get(userId).subscribe((permissions: PermissionModel[]>) => { 
      this.permissions$.next(permissions) 
    });

  }

  authorize(requirement: Requirement, id: number) : Observable<boolean> {

    switch(requirement) { 

      case Requirement.Create:

        return this.permissions$.asObservable().pipe(
          map(permissions => permissions.find(x => x.id === id)),
          map(permission => permission ? ['Admin', 'Client'].some(x => x === permission.name) : false    
          })
        );

    } 

    return of(false);

  }
@指令({
选择器:“[授权]”
})
导出类authorized指令实现OnInit{
要求:要求;
id:编号;
@Input()设置授权(要求:字符串){
本要求=要求[要求];
}
@Input()设置授权id(id:编号){
this.id=id;
}
构造函数(私有模板:TemplateRef,私有容器:ViewContainerRef,私有授权服务:授权服务){}
ngOnInit(){
this.authorizationService.authorization(this.requirement,this.id).pipe(
distinctUntilChanged()
).订阅(x=>{
x?this.container.createEmbeddedView(this.template):this.container.clear();
});
}
}
授权服务

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

export class AuthorizeDirective implements OnInit {

  requirement: Requirement;
  id: number;

  @Input() set authorize(requirement: string) {
    this.requirement = Requirement[requirement];
  }

  @Input() set authorizeId(id: number) {
    this.id = id;
  }

  constructor(private template: TemplateRef<any>, private container: ViewContainerRef, private authorizationService: AuthorizationService) { }

  ngOnInit() { 

    this.authorizationService.authorize(this.requirement, this.id).pipe(
      distinctUntilChanged()
    ).subscribe(x => {
      x ? this.container.createEmbeddedView(this.template) : this.container.clear();
    });

  }

}
@Injectable({ 
  providedIn: 'root' 
})

export class AuthorizationService {

  private notifier: Subscription;

  private permissions$: BehaviorSubject<PermissionModel[]> = new BehaviorSubject<PermissionModel[]>([]);

  constructor(private noteService: NoteService, private permissionService: PermissionService, private authenticationService: AuthenticationService) { 

    this.getPermissions();

    // Update permissions if user permissions were modified
    this.notifier = this.noteService.get().subscribe((note: Note) => { 

      if (note.code == NoteCode.PermissionsModified) {
        this.getPermissions();
      }

    });

  }

  private getPermissions() {

    let userId: this.authenticationService.getUserId();

    this.permissionService.get(userId).subscribe((permissions: PermissionModel[]>) => { 
      this.permissions$.next(permissions) 
    });

  }

  authorize(requirement: Requirement, id: number) : Observable<boolean> {

    switch(requirement) { 

      case Requirement.Create:

        return this.permissions$.asObservable().pipe(
          map(permissions => permissions.find(x => x.id === id)),
          map(permission => permission ? ['Admin', 'Client'].some(x => x === permission.name) : false    
          })
        );

    } 

    return of(false);

  }
@可注入({
providedIn:'根'
})
导出类授权服务{
私人通知:订阅;
私有权限$:BehaviorSubject=新的BehaviorSubject([]);
构造函数(私有noteService:noteService,私有permissionService:permissionService,私有authenticationService:authenticationService){
这是getPermissions();
//如果修改了用户权限,则更新权限
this.notifier=this.noteService.get().subscribe((注意:note)=>{
if(note.code==NoteCode.PermissionsModified){
这是getPermissions();
}
});
}
私有getPermissions(){
let userId:this.authenticationService.getUserId();
this.permissionService.get(userId).subscribe((权限:PermissionModel[]>)=>{
this.permissions$.next(权限)
});
}
授权(需求:需求,id:编号):可观察{
开关(要求){
案例要求。创建:
返回此.permissions$.asObservable().pipe(
映射(权限=>permissions.find(x=>x.id==id)),
映射(权限=>permission?['Admin','Client']。某些(x=>x==permission.name):false
})
);
} 
归还(假);
}
组件

export class PostComponent implements OnInit {

  postId: number;

  constructor(private route: ActivatedRoute, private authorizationService: AuthorizationService) { }

  ngOnInit() {

    this.route.paramMap.subscribe(parameters => {
      this.postId = parameters.has('postId') ? +parameters.get('postId') : undefined;
    })

  }

  public createPost() {
    // Create Post
  }

  // Method used in second example that uses `ngIf` and not the directive
  public authorize(requirement: string, id: number) : Observable<boolean> {
    return this.authorizationService.authorize(Requirement[requirement], id);
  }

}
导出类后组件实现OnInit{
posted:编号;
构造函数(私有路由:ActivatedRoute,私有授权服务:授权服务){}
恩戈尼尼特(){
this.route.paramMap.subscribe(参数=>{
this.postId=parameters.has('postId')?+parameters.get('postId'):未定义;
})
}
public-createPost(){
//创建帖子
}
//第二个示例中使用的方法,该方法使用'ngIf',而不是指令
公共授权(要求:字符串,id:编号):可观察{
返回此.authorizationService.authorize(需求[需求],id);
}
}

我在指令中做错了什么?

与其将指令逻辑放入
ngOnInit
中,不如尝试将其放入
ngOnChange
。我刚刚尝试过,但遇到了同样的问题