首页 > 解决方案 > Angular:不能使用异步管道

问题描述

我正在尝试使用模板中的异步管道解析为布尔值的可观察对象来显示微调器。observable 的值在服务中设置。我无法弄清楚出了什么问题。可观察值似乎解析为未定义。为什么这行不通?

是为示例创建的 stackblitz。

标签: angulartypescript

解决方案


您不应该使用 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);
}

推荐阅读