逐个调用Angular2函数,一个接一个

时间:2017-04-10 15:12:56

标签: javascript function angular typescript

我在Angular2项目中有一个服务,它接受一些参数并返回一个值列表来填充表单上的下拉菜单。当表单组件初始化时,我需要使用不同的参数多次调用相同的服务来定义许多不同的下拉菜单,但是如果我将它们全部调用,则最后一个称为clobbers以前的那些,大概是因为后续调用是覆盖的或取消之前的提取。

我已经将每个调用分成了他们自己的函数,但是我需要一种方法来串联调用每个函数,这样第二个函数就不会被调用,直到第一次完成。每个函数都可以单独工作,但是如果我调用多个函数,则只有最后一个函数成功,第一个函数失败并且错误(因为服务本身在完成之前使用新参数调用时终止当前获取)。

 this.fetchValueListOne();
 this.fetchValueListTwo();
 this.fetchValueListThree();

我试图通过承诺来完成这项工作,但是我必须快速通过我想要访问功能的服务,然后再次无法获得结果数据 - 每项服务call接受三个参数,然后设置在组件中定义并在表单上使用的特定this.valueList []变量。

我还尝试创建一个函数列表作为变量然后迭代它们,但是我遇到了与promises相同的范围问题。

该服务返回一个Observable,函数订阅该Observable,检索数据并将其分配给下拉值列表绑定到的组件中的数组变量。

函数看起来像这样:

fetchValueListOne() {
      this.dataSvc.getValueList('Val-List-One', this.stateSvc.currentContext, this.stateSvc.currentLanguageCode)
          .map(response => response.json())
          .subscribe(
          data => {
              this.valListOne = data;
          },
          err => console.log('Error', err),
          () => {
              console.log('this.valListOne', this.valListOne);
          }
          );
  }

2 个答案:

答案 0 :(得分:3)

SrAxi指出了我正确的方向,最终我解决了以下问题,其中Promise被证明是最佳解决方案,特别是Promise / .then机制很好地解决了问题。

  fetchValueList(listCode): Promise<any> {
      return this.dataSvc.getValueList(listCode, this.stateSvc.currentContext, this.stateSvc.currentLanguageCode)
          .map(response => response.json())
          .toPromise();
  }

  initializeDropDowns() {
      this.fetchValueList('First-Val-List')
          .then(data => {
              this.firstValList = data;
              return this.fetchValueList('Second-Val-List')
          }).then(data => {
              this.secondValList = data;
              return this.fetchValueList('Third-Val-List')
          }).then(data => {
              this.thirdValList = data;
          })  }

我在组件中定义了函数,然后在ngOnInit中调用了initializeDropDowns()。

fetchValueList函数返回一个Promise,因此第一个调用传递第一个listCode,当Promise解析时,返回值位于.then块中的数据变量中,我们可以将它分配给this.firstValList变量。当函数返回数据时,我们知道服务已经完成,并且使用第二个listCode再次调用是安全的,返回值在下一个.then块的数据变量中,我们将它分配给this.secondValList变量。 / p>

我们可以根据需要多次链接这个以填充所有变量,在最后一个代码块中我们只是省略return语句并且块终止。

这是一个非常具体的用例,我们有一个单独的服务,需要在组件初始化时多次调用,并且服务必须完成其获取并返回一个值才能再次调用,但是在这种情况下,Promise / .then方法是理想的。

答案 1 :(得分:1)

收到数据时调用函数。如:

    this.fetchValueListOne().subscribe((firstData) => {
            this.fetchValueListTwo(firstData);
            // Do something with firstData
        }
    );

    this.fetchValueListTwo().subscribe((secondData) => {
            this.fetchValueListThree(secondData);
            // Do something with secondData
        }
    );

    this.fetchValueListThree().subscribe((thirdData) => {
            // Do something with thirdData
        }
    );

并将这些函数声明为Observable,例如:

public fetchValueListOne(): Observable<any> { // Get firstData }
public fetchValueListTwo(): Observable<any> { // Get secondData}
public fetchValueListThree(): Observable<any> { // Get thirdData}

通过这种方式,您可以确定在调用函数时,您可以获得前一个函数。

相关问题