问题
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