Shoaib Iqbal
Shoaib Iqbal

Reputation: 2730

proeceed the execution once a function has returned in Angular 4

I have a function which uses web3.js to create a new account and return the account address. Here is my service

@Injectable()
export class ContractsService {
  private web3: any;
  public acc_no: any;

  public createAccount(): any {
      this.web3.personal.newAccount('abc123', function (error, result) {
      console.log("in funct");
       if (!error) {
         this.acc_no = result;
       } else {
         this.acc_no = 0;
       }
     }
   );
  }

}

I want to call this function createAccount and once that function has done creating a new account I want my component to proceed the execution. Here is my component;s function calling this createAccount function.

registerUser() {
    if (this.signupData.username !== '' && this.signupData.password !== '' && this.signupData.firstname !== ''
      && this.signupData.lastname !== '') {
        this.contractService.createAccount();
        setTimeout(() => {
          console.log(this.contractService);
          }, 2000);
    }
  }

I have tried using timeout but no luck, I am getting undefined for it. Any thought?

UPDATE

I used promise in following way

public createAccount(): Promise<any> {
       this.web3.personal.newAccount('abc123',  (error, result) => {
      console.log("in funct");
       if (!error) {
           this.acc_no = result;
       } else {
           this.acc_no = 0;
       }
     }
   ).toPromise()
        .then(() => {
          return this.acc_no;
        });
  }

but i am getting this error enter image description here

Upvotes: 2

Views: 112

Answers (2)

Russell D
Russell D

Reputation: 346

To use toPromise() you need to include:

import 'rxjs/add/operator/toPromise';

Referencing:

Property 'toPromise' does not exist on type 'Observable<Response>'

Upvotes: 0

David
David

Reputation: 34435

Try that

 public createAccount(): Promise <number>
 {

 return new Promise((resolve, reject) => {
      this.web3.personal.newAccount('abc123',  (error, result) => {
      console.log("in funct");
       if (!error) {
         this.acc_no = result;
         resolve(result);
       } else {
         this.acc_no = 0;
         resolve(result);
         //OR reject();
       }
     }
   );
  }
}

registerUser()
{
   //...
    this.contractService.createAccount().then(acc_no => 
    {
       console.log(acc_no);
    });
}

Upvotes: 2

Related Questions