我有一个关于为Angular 2路线解析一些数据的问题。
我创建了一个解析器服务,它应该根据某些条件返回布尔值。
但是,我面临的问题是在resolve方法中我需要调用最后执行的this.hotelService.getAll().subscribe(hotels => this.hotels = hotels)
(在return语句之后)。
这是代码:
resolve(routeSnapshot: ActivatedRouteSnapshot) {
this.hotelService.getAll(this.authenticationService.getUser()
.subscribe((hotels) => {
this.hotels = hotels;
});
return this.hotelService.hasManyCorporations(this.hotels); // => clear true/false value returned
}
您可能会注意到,在return语句中,我试图将this.hotels值传递给hasManyCorporations方法,但是存在未定义,因为在执行return语句时尚未执行this.hotels = hotels
代码块。
如何应对这种情况,我有2-3秒的延迟?这是我的整个解析器服务:
@Injectable()
export class HasManyCorporationResolveService implements Resolve<any> {
private hotels: Hotel[];
constructor(
private corporationService: CorporationService,
private authenticationService: AuthenticationService,
private hotelService: HotelService
) { }
resolve(routeSnapshot: ActivatedRouteSnapshot) {
this.hotelService.getAll(this.authenticationService.getUser().id)
.subscribe((hotels) => {
this.hotels = hotels;
});
return this.hotelService.hasManyCorporations(this.hotels); // clear true/false value returned
}
}