我需要从订阅服务调用中返回值。这是我的代码
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将是未定义的。有没有办法做到这一点?
答案 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));