angular - Angular:不能使用异步管道
问题描述
我正在尝试使用模板中的异步管道解析为布尔值的可观察对象来显示微调器。observable 的值在服务中设置。我无法弄清楚出了什么问题。可观察值似乎解析为未定义。为什么这行不通?
这是为示例创建的 stackblitz。
解决方案
您不应该使用 aSubject()
或在 中执行 setLoader ngAfterViewInit
,此时您.next(true)
尚未订阅模板:
解决方案1:
export class AppComponent {
loading$: Observable<boolean>;
constructor(private myservice: MyService) {
this.loading$ = myservice.loading$;
}
ngAfterViewInit() {
this.myservice.setLoader(true);
}
}
解决方案2:
export class AppComponent {
loading$: Observable<boolean>;
constructor(private myservice: MyService) {
this.loading$ = myservice.loading$.pipe(
shareReplay(1)
);
}
ngOnInit() {
this.myservice.setLoader(true);
}
}
解决方案3:
private loadingSource = new ReplaySubject(1);
loading$ = this.loadingSource.asObservable();
constructor() { }
setLoader(isLoading: boolean) {
this.loadingSource.next(isLoading);
}
推荐阅读
- javascript - 如何在数组中打印唯一的数字
- ruby-on-rails - 注册时验证密码
- javascript - 如何使值来自用户输入的对象
- android - 用户是否从 HTML 表单中选择联系人?
- java - 线性规划 - 如何将变量设置为 0 或 1?
- python - 在 matplotlib 中制作 45 度向量
- css - 使用 CSS Grid auto-fit 时,我可以让网格单元格扩展以适应其内容吗?
- sql-server - 如何根据多行的各种条目 ID 的条目日期从数据库中获取最新数据
- vue.js - 如何获得焦点以返回选择输入
- pandas - 将 KDB 查询返回到 pandas 数据框