在我的angular 7应用程序中,我试图将{[key : string] : string}
类型的字典对象从服务传递到组件。
当我console.log
对象时,控制台成功返回字典:{image : blob:http//..., model: blob:http//...}
但是当我尝试像这样访问image
值时:taskList['image']
返回undefined
;这没有任何意义。这是代码:
服务:
public resolveTasks(callback : Function){
forkJoin(...this.tasks).subscribe(async results => {
let refMap : {[key: string] : string} = {};
await results.forEach(async ref => {
ref = await this.makeRequest("GET", ref);
if(ref.type.includes('image')){
ref = URL.createObjectURL(ref); //create a url for the downloaded blob : blob:http://....
refMap['image'] = ref;
} else {
const id = Math.floor(1000 + Math.random() * 9000); //add random number identifier
ref = URL.createObjectURL(this.blobToFile(ref, `model${id}.obj`))
refMap['model'] = ref
}
});
callback(refMap); //{image:... , model: ....} loadContent is called here
this.tasks = []; //empty the task list
})
}
组件:
public ngOnInit() : void {
//setup
this.firebaseModel.resolveTasks(this.loadContent.bind(this));// pass loadContent as callback
}
private loadContent(taskList : {[key:string] : string}) : void {
console.log(taskList['image']) //trying to access blob by key, returns undefined
const model : any = taskList['model'];
const textureLoader = new THREE.TextureLoader(this.manager);
const texture : string = textureLoader.load(taskList['image']);
this.loadResources(model, texture, this.scene, this.renderer, this.container);
this.animate();
}
答案 0 :(得分:0)
问题出在我的service
:
这是工作代码:
await Promise.all(results.map(async (ref) =>{
ref = await this.makeRequest("GET", ref);
if(ref.type.includes('image')){
ref = URL.createObjectURL(ref);
refMap['image'] = ref;
} else {
const id = Math.floor(1000 + Math.random() * 9000); //add random number identifier
ref = URL.createObjectURL(this.blobToFile(ref, `model${id}.obj`))
refMap['model'] = ref
}
}));
在这里找到解决方案,结果是forEach循环只是触发了多个异步调用,而不是顺序地处理每个get请求。 这篇文章非常有用: