Angular return value from subscribe

人盡茶涼 提交于 2019-12-24 10:26:06

问题


I need to return value from subscribe of a service call. here is my code

export class RideDataSource extends DataSource<any> {

  rides: Ride[];

  constructor(private _rideService: RidesService,
              private _paginator: MatPaginator) {
    super();
  }

  connect(): Observable<Ride[]> {

this._rideService.getActiveRides(this._paginator.pageIndex, this._paginator.pageSize).subscribe(
      ridePage => {
        this.rides = ridePage.content;
        this._paginator.length = ridePage.totalElements;
      }
    );

    // i need to return  Observable.of(this.rides);
  }

  disconnect() {
    // No-op
  }

}

returning Observable.of(this.rides) won't work as this.rides will be undefined. is there any way to do this?


回答1:


Do not subscribe in the service, use the map operator instead and subscribe to connect():

connect(): Observable<Ride[]> {
  return this._rideService.getActiveRides(
    this._paginator.pageIndex, 
    this._paginator.pageSize
  ).pipe(
    map(ridePage => {
      this.rides = ridePage.content;
      this._paginator.length = ridePage.totalElements;
      return this.rides;
    })
  );
}

...

connect().subscribe(rides => console.log(rides));


来源:https://stackoverflow.com/questions/49418984/angular-return-value-from-subscribe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!