订阅的角度返回值 [英] Angular return value from subscribe

查看:75
本文介绍了订阅的角度返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过订阅服务电话返回值.这是我的代码

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
  }

}

返回Observable.of(this.rides)无效,因为this.rides是未定义的.有什么办法吗?

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

推荐答案

请勿订阅该服务,请使用地图运算符,然后订阅connect():

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

这篇关于订阅的角度返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆