如果rxjs不对更改做出反应,那么可观察的目的是什么?

时间:2019-11-18 14:09:39

标签: angular typescript rxjs

我有一组项目,并使用of将其包装在可观察的范围内。
可观察对象是在填充数组之前创建的。
最终填充数组时,传递给observable callback的{​​{1}}不会被调用。

据我了解,subscribe仅对列表中已存在的项目称为observable,在我看来,这是多余的。

我有一种情况,我在带有callback的{​​{1}}管道中使用此可观察对象,并且这个响应正确,但是当我将可观察对象作为*ngFor粘贴到{{1 }}或将async传递给data source函数,那么最终填充列表时我什么也没得到。

mat-table管道在后台执行什么操作,而我不见了?

callback

subscribe管道已正确更新,但是我想这可能是因为asyncexport 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

2 个答案:

答案 0 :(得分:2)

您的可观察对象不会对更改做出反应,因为它是使用of从静态数组创建的,该数组仅发出一次。您可以改用这些方法。

DiscoveryService

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();
  }
}

DeviceListComponent

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">

答案 1 :(得分:0)

export class DiscoveryService {
  construct(private http: HttpClient) {
  }

  getDeviceList(): Observable<DeviceModel[]> {
     return this.http.get<DeviceModel[]>('yourUrl');
  }
}

或者如果您要缓存它:

export class DiscoveryService {
  private deviceList$: Observable<DeviceList[]>;

  construct(private http: HttpClient) {
  }

  getDeviceList(): Observable<DeviceModel[]> {
     if (!this.deviceList$) {
       this.deviceList$ = this.http.get<DeviceModel[]>('yourUrl').pipe(
         shareReplay(1),
       );
     }

    return this.deviceList$;
  }
}
相关问题