尝试通过键访问值时,Typescript字典对象返回未定义的

时间:2019-02-26 11:59:01

标签: typescript angular7 angular-services

在我的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();
    }

1 个答案:

答案 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请求。 这篇文章非常有用:

Using async/await with a forEach loop