为什么在点击两次后获取值? +承诺

时间:2018-02-25 03:55:35

标签: angular asynchronous angular-promise

我在处理角度的promise函数时缺乏对异步操作的理解。所以基本上,我试图从promise方法中获取一个值并将其分配给组件中的全局变量。但是,当我单击一次按钮时,我无法检索该值,并且在我再次单击按钮后它最终开始显示该值。

我点击一次

时出错

Cannot read property 'matchId' of undefined

我点击两次后获得的价值:

3

HTML:

<button type="submit" (click)="loadInfo(form)">Submit</button>

服务:

@Injectable()
export class Web3Service {
    constructor...

    getInfo(address: string): Promise<any> {
        return this.TestBetting.deployed().then((instance) => {
          return instance.getInfo.call(address);
        })
        .then((value) => {
          var serialized = this.itemsService.getSerialized<IGetInfo>(value); 
          return this.mappingService.mapValueToGetInfo(serialized); 
        })
        .catch((e) => {
          console.log(e);
        });
    }  
}

组件:

export class HomeComponent {
    infoMapped: any;

    constructor(private web3Service: Web3Service) {}

    loadInfo(): void {
        var test = this.web3Service.getInfo(this.address); 
        test.then((value) => {
            this.infoMapped = value;
        })

        // this.infoMapped.matchId is undefined on a first attempt
        var length = this.infoMapped.matchId;
        for (var i = 0; i < length; i++) {
        //...
        }
    }
}

需要修复哪些内容才能在仅按一次按钮后检索infoMapped值?

1 个答案:

答案 0 :(得分:1)

问题仍然是代码 test.then()(即for)将在<{strong> this.infoMapped = value;之前执行因为{ {1}}仅在this.infoMapped = value;承诺解决时执行,并且只会在 test运行后解析一段时间。

我建议:移动&#34;处理&#34;新方法的逻辑,并从for

调用它

所以,这个:

.then()

会变成这样:

loadInfo(): void {
    var test = this.web3Service.getInfo(this.address); 
    test.then((value) => {
        this.infoMapped = value;
    })

    // this.infoMapped.matchId is undefined on a first attempt
    var length = this.infoMapped.matchId;
    for (var i = 0; i < length; i++) {
    //...
    }
}