首页 > 解决方案 > 如果 rxjs observable 不对变化做出反应,它的目的是什么?

问题描述

我有一个项目数组,我使用of.
可观察对象是在填充数组之前创建的。
最终填充数组时,不会调用observable callback传递给的对象。subscribe

据我了解,observable仅将其callback用于列表中已有的项目,在我看来,这使得它变得多余。

我有一个案例,我在*ngForwithasync管道中使用这个 observable,这个反应正确,但是当我将 observable传递data source给 amat-table或者我将我传递callbacksubscribe函数时,当列表最终被填充时,我什么也得不到.

管道在幕后做了什么async,而我失踪了?

export class DiscoveryService {
  private deviceList: DeviceModel[] = [];

  constructor() {
  }

  getDeviceList(): void {
    // Get devices from server and push them in the deviceList
  }

  observeDeviceList(): Observable<DeviceModel[]> {
    return of(this.deviceList);
  }
}

export class DeviceListComponent implements OnInit {
  deviceList$: Observable<DeviceModel[]>;

  constructor(private discoveryService: DiscoveryService) { }

  ngOnInit() {
    this.deviceList$ = this.discoveryService.observeDeviceList();

    // This callback get's called only once at the beginning, with an empty list
    this.deviceList$.subscribe(devices => console.log('got devices: ' , devices));

    // When the devices are retrieved from the server, the callback 
    //from the above subscription is not triggered again
    this.discoveryService.getDeviceListx();
  }
}

管道得到正确更新,async但我想这可能是因为ngOnInit在运行之前调用了*ngFor。我不确定。

<mat-nav-list *ngFor="let device of deviceList$ | async">

标签: angulartypescriptrxjs

解决方案


您的 observable 不会对更改做出反应,因为它是从静态数组创建的,使用of它只发出一次。这是您可以做的事情。

发现服务

export class DiscoveryService {
  private _deviceList$ = new BehaviorSubject<DeviceModel[]>([]);

  construct() {
    this.fetchDeviceList();
  }

  get deviceList$() {
    return this._deviceList$.asObservable();
  }

  fetchDeviceList() {
     this.http.get<DeviceModel[]>('yourUrl').pipe(
       tap((list: DeviceModel[]) => this._deviceList$.next(list))
     ).subscribe();
  }
}

设备列表组件

export class DeviceListComponent implements OnInit {
  private _deviceList$: Observable<DeviceModel[]>;

  constructor(private discoveryService: DiscoveryService) { }

  ngOnInit() {
    this._deviceList$ = this.discoveryService.deviceList$;
  }
}

那么这在您的模板中应该可以正常工作

<mat-nav-list *ngFor="let device of _deviceList$ | async">

推荐阅读