Subject.next没有在ngOnInit中触发

use*_*686 8 subject rxjs angular

有谁为什么这个代码(从主题初始化一个值)不起作用?有没有错误或设计?我究竟做错了什么?

TS

import { Component, OnInit } from '@angular/core';
import { Subject } from "rxjs";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.styl']
})
export class AppComponent implements OnInit {
  itemSupplier$: Subject<any[]> = new Subject<any[]>();

  items: any[] = [
    {name: 'Item 1', value: 'item1'},
    {name: 'Item 2', value: 'item2'},
  ];

  ngOnInit(){
    this.itemSupplier$.next(this.items);
  }
}
Run Code Online (Sandbox Code Playgroud)

HTML

<ul>
    <li *ngFor="let item of itemSupplier$ | async">{{item.name}}</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

Ste*_*doo 9

这似乎是一个时间问题,如果你把它扔进一个setTimeout就行了.

setTimeout(() => this.itemSupplier$.next(this.items), 0)

编辑

使用BehaviorSubject实际上是一个更好的主意.这将在订阅时提供最后一个值.

  • 将`Subject`更改为`BehaviorSubject`,如:`itemSupplier $:BehaviorSubject <any []> = new BehaviorSubject <any []>([]);`确实有效. (8认同)
  • 我已经对其进行了角度调试,看起来异步管道直到 ngOnInit 之后才注册订阅,因此您可以在没有订阅的情况下调用 next 。 (2认同)