【发布时间】:2020-03-31 08:49:43
【问题描述】:
我有一个显示或隐藏 HTML 元素 StackBlitz 的指令:
<div *authorize="'A'">
Visible when letter is A
</div>
授权指令是:
@Directive({
selector: '[authorize]'
})
export class AuthorizeDirective implements OnInit {
letter: string;
@Input() set authorize(letter: string) {
this.letter = letter;
}
constructor(private element: ElementRef, private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef, private authorizationService: AuthorizationService) { }
ngOnInit() {
this.authorizationService.authorize(this.letter).subscribe(x => {
x ? this.viewContainer.createEmbeddedView(this.templateRef) : this.viewContainer.clear();
});
}
}
授权服务及其授权方法是:
export class AuthorizationService {
private notifier: Subscription;
private data$: Observable<string[]>;
constructor(private noteService: NoteService) {
this.data$ = of(['A', 'B']);
this.data$.subscribe(x => console.log(x));
this.notifier = this.noteService.get().subscribe((code: number) => {
if (code == 0) {
this.data$ = of(['C', 'D']);
this.data$.subscribe(x => console.log(x));
}
});
}
authorize(letter: string) : Observable<boolean> {
return this.data$.pipe(
map(data => data.indexOf(letter) > -1)
);
}
}
在真实场景中,data$ 是使用 HTTPClient 从 API 获取的。
NoteService 是:
export class NoteService {
private subject = new Subject<number>();
send(code: number) {
this.subject.next(code);
}
clear() {
this.subject.next();
}
get(): Observable<number> {
return this.subject.asObservable();
}
}
当发出带有代码 0 的 note 时,data$ 也会更新...
这应该会更新使用该指令的元素的可见性。
在 StackBlitz 示例中,通过单击应显示带有 C 的 Div 按钮。
但它并没有这样做......如何触发它?
【问题讨论】:
-
我真的不清楚!你想从服务中访问指令吗?要不然是啥?你能提供示例工作演示吗?
-
否...在服务中,我正在更新
if (note.code == 0) { }内的data$。发生这种情况时,我希望指令更新元素的可见性。就像再次调用授权一样......因为使用新数据$授权的结果可能会有所不同。 -
这是help吗?我的意思是试试
ngOnChanges() -
以哪种方式?使用
BehaviorSubject?不确定如何将其集成到指令中,或者AuthorizationService上是否会发生某些变化。 -
给我一个 stackblitz 试试!
标签: angular typescript rxjs angular8