【问题标题】:proeceed the execution once a function has returned in Angular 4一旦函数在 Angular 4 中返回,就继续执行
【发布时间】:2018-08-17 08:17:17
【问题描述】:

我有一个函数,它使用 web3.js 创建一个新帐户并返回帐户地址。这是我的服务

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

}

我想调用此函数createAccount,一旦该函数创建了一个新帐户,我希望我的组件继续执行。这是我的组件调用此 createAccount 函数的函数。

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

我尝试过使用超时但没有运气,我对此没有定义。有什么想法吗?

更新

我按照以下方式使用了promise

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

但我收到此错误

【问题讨论】:

  • 使用ObservablePromise
  • 如果你想正确填充 acc_no 你需要使用箭头函数this.web3.personal.newAccount('abc123', (error, result) =>...`。然后,您可以将其包装在一个承诺中并在成功时调用 resolve
  • @David 检查有问题的更新
  • @Faisal 请检查问题中的更新
  • @Shoaib Iqbal 检查我的答案

标签: angular web3js web3


【解决方案1】:

要使用toPromise(),您需要包括:

import 'rxjs/add/operator/toPromise';

参考:

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

【讨论】:

    【解决方案2】:

    试试看

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

    【讨论】:

      猜你喜欢
      • 2013-03-31
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 2018-06-21
      • 1970-01-01
      • 2021-12-02
      • 2021-08-02
      • 1970-01-01
      相关资源
      最近更新 更多