简体   繁体   中英

Angular return value from subscribe

I need to return a value from the 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?

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

RideDataSource:

export class RideDataSource  {

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

Some Component:

export class SomeComponent implements OnInit {

  constructor(private rideDataSource: RideDataSource) { }

  ngOnInit() {
    this.rideDataSource.connect().subscribe(rides => console.log(rides));
  }
}

If you need the data in the component template, then you can do the following:

Some Component Class:

export class SomeComponent {

  rides = this.rideDataSource.connect()

  constructor(private rideDataSource: RideDataSource) { }
}

Some Component Template:

{{ rides | async }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM