订阅的角度返回值

时间:2018-03-22 01:11:24

标签: angular rxjs angular-material angular5

我需要从订阅服务调用中返回值。这是我的代码

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
  }

}

返回Observable.of(this.rides)将不起作用,因为this.rides将是未定义的。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:5)

请勿在服务中订阅,请改用map运算符并订阅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));