如何在AngularJS中返回对调用函数的响应?

时间:2018-06-01 08:30:37

标签: angularjs

我正在调用此方法testDataService,该方法在同一个JS文件中定义。此方法返回从API调用获取的列表。我想将该值设置为模型并返回模型对象。但我的返回函数在我的API返回响应之前被调用。我怎样才能确保只有在上述if块从API获取数据后才会调用return函数。

       getTestData(model) {

            model.name = "practice";
            model.value = 2;

    // this if loop is calling an API and setting up data into model.

           if(this.model.form.length>0 && this.model.form[0].entityName === 'test'){
           let responseList;
           this.testDataService(this.model).then(response => {
           responseList = response;
           model.class = responseList;

    });
    }

           return this.model;

       // this return function is getting called before the api returns its data. How can i make sure this return will get called only after the above if block get the data from API.

    }



    This is method definition

        testDataService(model) {
          let profileType = "test";
          let profileId = "test_profile";
          let configCategory = "test";
          return this.referenceDataService.getTestData(profileType, profileId, configCategory);
        }

1 个答案:

答案 0 :(得分:1)

您需要从回调传递return语句,而不是将其放在外面。

getTestData(model) {
  model.name = "practice";
  model.value = 2;

 // this if loop is calling an API and setting up data into model.

 if (this.model.form.length > 0 && this.model.form[0].entityName === 'test') {
    this.testDataService(this.model).then(response => {
        let responseList = response;
        model.class = responseList;
        return this.model;
    }).then(response => {
        return null;
    });
  }
}

testDataService(model) {
 let profileType = "test";
 let profileId = "test_profile";
 let configCategory = "test";
 return this.referenceDataService.getTestData(profileType, profileId, configCategory);
}