0

const variable is not re-assigning in method which I am calling from component ngOnInit method.

ec2.service.ts

private _status = false;

getStatus() {
    const params = {
        InstanceIds: [ 'i-xxxxxxxxxxxxxxx' ]
    };
    ec2.describeInstanceStatus(params, function(err, data) {
        if (err) {
            console.log(err, err.stack);
        } else {
            console.log(data);
            if (data.InstanceStatuses.length === 0) {
                this._status = true;
            }
        }
    });
    console.log(this._status);
    return this._status;
}

component.ts

constructor(public service: EC2Service) { }
ngOnit() {
    console.log(this.service.getStatus());
}

Here the condition is true. But it is returning false instead true.

Bhargav Teja
  • 431
  • 6
  • 19
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – 1565986223 Apr 02 '19 at 12:01

2 Answers2

0

Since ec2.describeInstanceStatus performs an async operation, you need to wait until it finishes. You can use async/await syntax.

And you better use arrow function in order not lose scope within the callback function.

async getStatus() {
    const params = {
        InstanceIds: [ 'i-xxxxxxxxxxxxxxx' ]
    };
    await ec2.describeInstanceStatus(params, (err, data) => {
        if (err) {
            console.log(err, err.stack);
        } else {
            console.log(data);
            if (data.InstanceStatuses.length === 0) {
                this._status = true;
            }
        }
    });
    console.log(this._status);
    return this._status;
}
Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35
  • When I am trying like this, It returns **ZoneAwarePromise {__zone_symbol__state: null, __zone_symbol__value: Array(0)}** not true or false – Bhargav Teja Apr 02 '19 at 16:50
0

Your method describeInstanceStatus perform async operation. To get the result from async operation you can do using promise and async/await like below

    getStatus() {
      return new Promise((resolve, reject) => {
      const params = {
            InstanceIds: [ 'i-xxxxxxxxxxxxxxx' ]
        };
          ec2.describeInstanceStatus(params, function(err, data) {
            if (err) {
               reject(err)
            } else {
                console.log(data);
                if (data.InstanceStatuses.length === 0) {
                   resolve(true)
                }
                reject(false)
            }
        });
    });
   }

component.ts

constructor(public service: EC2Service) { }
async ngOnit() {
    const result = await this.service.getStatus();
     console.log(result)
}
narayansharma91
  • 2,273
  • 1
  • 12
  • 20