在尝试按键访问值时,typescript字典对象返回undefined

问题描述 投票:0回答:1

在我的角度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();
    }
typescript angular7 angular-services
1个回答
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请求;这篇文章非常有用:

Using async/await with a forEach loop

© www.soinside.com 2019 - 2024. All rights reserved.