Объект словаря Typescript, возвращающий неопределенное значение при попытке доступа к значению по ключу - PullRequest
0 голосов
/ 26 февраля 2019

В моем приложении angular 7 я пытаюсь передать объект словаря типа {[key : string] : string} из моего сервиса в мой компонент.

Когда я console.log объект, консоль успешно возвращает словарь: {image : blob:http//..., model: blob:http//...}

Но когда я пытаюсь получить доступ к значению image следующим образом: taskList['image'] возвращает1010 *;что не имеет никакого смысла.Вот код:

сервис:

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 голосов
/ 01 марта 2019

Проблема была в моем 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 последовательно;этот пост был очень полезен:

Использование async / await с циклом forEach

...