RXJS:observable 未发送新变量值

RXJS: new variable value isn't being sent by observable

我是 RxJs 的新手,我正在尝试创建一个简单的 Observable,将新变量值发送到组件。

不确定我做错了什么,我想 Observable 无法识别变量正在更改,但希望得到一些解释...

我的组件:

export class NamesListComponent implements OnInit {

  constructor(private dataService: DataService) { }

  public numArr: number[] = [];
  subscription: Subscription 

  ngOnInit(): void {

   this.subscription = this.dataService.getNum.subscribe((value: number) => {
       this.numArr.push(value);
    })
  }
  
  ngOnDestroy(): void {
    this.subscription.unsubscribe()
  }
}

我的服务:

export class DataService {


  private privateNum: number = 0;

  getNum = new Observable(subscriber => {
    setInterval(() => {
      this.privateNum++
    }, 1000);

    subscriber.next(this.privateNum)
  })

  constructor() {
  }
}

您应该尝试使用 BehaviorSubject 或 ReplaySubject。

此外,我认为 next() 应该在 setInterval() 中:

getNum = new Observable(subscriber => {
    setInterval(() => {
      this.privateNum++;
      subscriber.next(this.privateNum)
    }, 1000);
  })

问题在于 angular 的更改检测对引用有效。由于您只是在数组中推送一个值,因此引用不会更改并且更改检测不会 运行.

尝试使用以下代码段:

export class NamesListComponent implements OnInit {

  constructor(private dataService: DataService) { }

  public numArr: number[] = [];
  subscription: Subscription 

  ngOnInit(): void {

   this.subscription = this.dataService.getNum.subscribe((value: number) => {
       this.numArr = [...this.numArr, value]; // Using the spread operator, this create a new array (a new reference) and triggers change detection
    })
  }
  
  ngOnDestroy(): void {
    this.subscription.unsubscribe()
  }
}

我假设您在模板中显示带有 *ngFor 的数组,如果是这种情况,您还可以检查 Angular ngForOf doc,尤其是 trackBy 函数。