来自订阅的角度返回值 [英] 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
}
}
返回 Observable.of(this.rides)
将不起作用,因为 this.rides
将是 undefined
.有没有办法做到这一点?
Returning Observable.of(this.rides)
won't work as this.rides
will be undefined
. Is there any way to do this?
推荐答案
不要在服务中订阅,使用map 运算符并订阅 connect()
.
Do not subscribe in the service, use the map operator instead and subscribe to connect()
.
骑行数据源:
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;
})
);
}
}
某些组件:
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:
一些组件类:
export class SomeComponent {
rides = this.rideDataSource.connect()
constructor(private rideDataSource: RideDataSource) { }
}
一些组件模板:
{{ rides | async }}
这篇关于来自订阅的角度返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文