为什么异步管道不订阅在构造函数中初始化的可观察对象

Why does the async pipe not subscribe to observable inialized in the constructor

查看这个 plunkr 的插图:https://plnkr.co/edit/Tm4AW0sU0pumBA8I?open=lib%2Fapp.ts&deferRun=1

组件 1,我在 class 初始值设定项中声明所有内容:

@Component({
  template: '{{ data$ | async | json }}',
  selector: 'app-data'
})
export class AppData {
  readonly id$ = new Subject();
  readonly data$ = this.id$.pipe(
    switchMap(id => of(`id = ${id}`))
  );

  @Input()
  set id(val: number) {
    this.id$.next(val)
  }
}

在组件 2 中我创建了可观察的 onInit:

@Component({
  template: '{{ data$ | async | json }}',
  selector: 'app-data-oninit'
})
export class AppDataOnInit implements OnInit {

  @Input()
  id: number;

  data$: any;


  ngOnInit(): void {
    this.data$ = of(`id = ${this.id}`)
  }
}

我正在尝试在组件构造函数或 class 初始化器中声明可观察对象,但异步管道并未在那里订阅它。但是,如果我在 ngOnInit 中实例化可观察对象,它会按预期工作。

我整天都在寻找对此的解释,但一无所获。这里缺少的拼图是什么?

我觉得在创建 class 时声明可观察对象更有意义。

异步管道正在订阅您的 data$,但此订阅发生在 id$ 发出之后。如果你想让迟到的订阅者收到之前的发射,你可以使用 ReplaySubject 而不是普通的 Subject:

readonly id$ = new ReplaySubject(1);