【问题标题】:execute a code only when a particular method completes an API request in angular 4仅当特定方法以角度 4 完成 API 请求时才执行代码
【发布时间】:2020-11-14 10:16:18
【问题描述】:

假设我有两种方法:方法一和方法二。方法一在方法二内部有一个调用,如下所示:

variable;

methodOne(){
    this.variable;
    // A API call which sets the value of "variable"
};

methodTwo(){
    this.methodOne();

    if(this.variable!= null){
        // using data in variable for other operations
    }
}

现在的问题是当methodTwo 被调用时,它在内部调用methodOne,它通过API 返回的数据设置“变量”的值。但是methodTwo中的methodOne调用之后的代码在设置“变量”数据之前执行,并且变量的值始终为null。

【问题讨论】:

    标签: angular api angular-material observable


    【解决方案1】:
    methodOne(){
          
       // return this.http.get('whatever');
    
    };
    
    methodTwo(){
    
          this.methodOne().subscribe((whateverResponse)=>{
    
              // set this.variable here with whateverResponse
    
              if(this.variable !=null){
                 // do whatever here.
              }
    
          });
    }
    

    【讨论】:

      猜你喜欢
      • 2022-11-23
      • 2019-05-25
      • 2020-11-18
      • 1970-01-01
      • 1970-01-01
      • 2020-01-07
      • 2014-08-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多