gpt4 book ai didi

javascript - 让 Angular 解析器等待图像

转载 作者:行者123 更新时间:2023-12-01 00:03:35 25 4
gpt4 key购买 nike

我该怎么做才能让解析器等待,直到它从 API 获取图像。现在,Angular 会等待接收数据,显示页面,然后尝试获取帖子的图像。

@Injectable()
export class DataResolverService implements Resolve<any> {
constructor(
private router: Router,
private API: ApiService
) {}

resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<any> | Observable<never> {
return this.API.getPostById(route.params.id).pipe(
map(response => {
if (response["images"]) {
const images = [];
response["images"].forEach(image => {
this.API.getImageById(image.id).subscribe(
(img: any) => {
const imageObject = {
url: window.URL.createObjectURL(img),
};
images.push(imageObject);
}
);
});
response["images"] = images;
return response;
}

return response;
})
);
}
}

最佳答案

尝试:

@Injectable()
export class DataResolverService implements Resolve<any> {
constructor(
private router: Router,
private API: ApiService
) {}

resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<any> | Observable<never> {
return this.API.getPostById(route.params.id).pipe(
switchMap(response => { // change this into a switchMap
if (response["images"]) {
return combineLatest(
// combine all of the request for the images
...response["images"].map(image => this.API.getImageById(image.id)),
).pipe(
map(images => images.map(image => ({ url: window.URL.createObjectURL(image) })),
map(images => ({ response: images })), // This map may be unnecessary
);
} else {
return of([]);
}
})
);
}
}

这应该可以帮助你开始。您的方法的问题是您正在内部可观察中订阅,并且我认为路由解析器没有在等待它。

关于javascript - 让 Angular 解析器等待图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60545346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com