[英]Typescript dictionary object returning undefined when trying to access value by key
In my angular 7 app I'm trying to pass a dictionary object of type {[key : string] : string}
from my service to my component. 在我的angular 7应用程序中,我试图将{[key : string] : string}
类型的字典对象从服务传递到组件。
When I console.log
the object, the console successfully returns the dictionary: {image : blob:http//..., model: blob:http//...}
当我console.log
对象时,控制台成功返回字典: {image : blob:http//..., model: blob:http//...}
But when I try to access the image
value like so: taskList['image']
it returns undefined
; 但是,当我尝试像这样访问image
值时: taskList['image']
它返回undefined
; which doesnt make any sense. 这没有任何意义。 Here's the code: 这是代码:
service: 服务:
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
})
}
component: 零件:
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();
}
The issue was in my service
: 问题出在我的service
:
This is the working code: 这是工作代码:
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
}
}));
The solution was found here, turns out that a forEach loop simply fires out multiple asynchronous calls instead of processing each get request sequentially; 在这里找到了解决方案,结果是forEach循环只是触发了多个异步调用,而不是顺序地处理每个get请求。 this post was very useful: 这篇文章非常有用:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.