Why getting the value after clicking it twice? + P

2019-08-25 14:18发布

问题:

I have a lack of understanding asynchronous operation while I'm dealing with a promise function in angular. So basically, I'm trying to get a value from a promise method and assign it to a global variable in a component. However, I am unable to retrieve the value when I click on a button once and it finally starts to show the value after I clicked on a button once more.

Error I get when I clicked it once:

Cannot read property 'matchId' of undefined

Value I get after I clicked it twice:

3

Html:

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

Service:

@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);
        });
    }  
}

Component:

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++) {
        //...
        }
    }
}

What needs to be fixed so that infoMapped value can be retrieved after clicking a button only once?

回答1:

The problem is still that code after the test.then() (i.e. the for) will execute before the this.infoMapped = value; because this.infoMapped = value; will only execute when the test promise resolves, and it will only resolve some time after the for runs.

What I suggest: move the "handling" logic to a new method and call it from the .then().

So, this:

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++) {
    //...
    }
}

Would become this:

loadInfo(): void {
    var test = this.web3Service.getInfo(this.address); 
    test.then((value) => {                 // <=== changed this line
        this.handleInfo(value)             // <=== changed this line
     });
}

handleInfo(value): void {                   // <=== added this whole method.
    this.infoMapped = value;

    var length = this.infoMapped.matchId;
    for (var i = 0; i < length; i++) {
    //...
    }
}