我有一个角度的应用程序,我试图获得一个图像旋转木马的资源阵列。我现在是如何设置它的,我有一个"getUrls()“方法来从数据库中获取urls,如下所示
http.service.ts:
getUrls() {
this.http
.get<string[]>(
'<DATABASE_LINK>'
)
.subscribe((imageUrls: string[]) => {
this.carouselService.setUrls(imageUrls);
});
}该方法调用方法"setUrls“将它们设置为存储在服务中的数组。
carousel.service.ts:
urls: string[] = [];
constructor() {}
setUrls(urls: string[] | []) {
this.urls = urls || [];
debugger;
}
getImages() {
debugger;
return this.urls;
}然后,在旋转木马组件中,我在ngOnInit中调用了前面的两个方法
图像-carousel.Component.ts:
ngOnInit(): void {
this.httpService.getUrls();
this.images = this.cService.getImages();
}然后,这将分配"setUrls()“方法设置的值,但出于某种原因,在设置Urls之前,它将到达"getImages()”方法。
我把"getImages()“行放到一个单独的方法中,然后单击一个按钮来调用它,这样我就可以确保所有的事情都按正确的顺序工作了,但是我想让它在组件初始化时完成所有这些工作。
我确信我错过了一些东西,所以任何事情都有帮助,即使我必须重构很多东西。
我尝试在"getUrls()“方法中使用”getUrls(抽头())“而不是订阅,但是它永远不会调用"setUrls()”方法。
发布于 2022-03-12 10:39:04
当getUrls()执行异步任务(即http.get )时,您必须等待获取映像,直到异步任务完成。
因此,可能的解决方案之一是,您可以从您的http.service.ts服务中返回可观察到的内容,在组件ngOnInit中可以在订阅中获取图像。
http.service.ts:
getUrls() {
return this.http
.get<string[]>(
'<DATABASE_LINK>'
)
.pipe(
map((imageUrls: string[]) => {
this.carouselService.setUrls(imageUrls);
})
);
}carousel.service.ts:
urls: string[] = [];
constructor() {}
setUrls(urls: string[] | []) {
this.urls = urls || [];
debugger;
}
getImages() {
debugger;
return this.urls;
}image-carousel.component.ts:
ngOnInit(): void {
this.httpService
.getUrls()
.subscribe(
() => {
this.images = this.cService.getImages();
}
);
}发布于 2022-03-12 06:33:38
由于getUrls()异步执行其工作,因此您不知道它何时完成并返回imageUrls。您必须稍微重构代码,如下所示
getUrls():Observable<string[]> {
return this.http
.get<string[]>(
'<DATABASE_LINK>'
);
}您的ngOnInit方法将得到如下更新
ngOnInit(): void {
this.httpService.getUrls()
.subscribe((imageUrls:string[])=>
{
this.images = imageUrls;
});
}发布于 2022-03-15 00:24:35
http.service.ts:
getUrls() {
return this.http
.get<string[]>(
'<DATABASE_LINK>'
)
.pipe(
map((imageUrls: string[]) => {
this.carouselService.setUrls(imageUrls);
})
);
}carousel.service.ts:
urls: string[] = [];
constructor() {}
setUrls(urls: string[] | []) {
this.urls = urls || [];
debugger;
}
getImages() {
debugger;
return this.urls;
}图像-carousel.Component.ts:
ngOnInit(): void {
this.httpService
.getUrls()
.subscribe(
() => {
this.images = this.cService.getImages();
}
);
}https://stackoverflow.com/questions/71445676
复制相似问题