我的指令中有三个功能: -
scope.fetchDetails = function(){
scope.a.data1 = scope.margin1;
scope.a.data2 = scope.margin2;
scope.getMargin(scope.a.data1,scope.a.data2);
}
scope.getMargin = function(data1,data2 {
ApiServices.getMargin(data1,data2).then(function (response) {
scope.selected = response.data;
scope.a.allValues = scope.selected.Values;
});
}
scope.getUser = function(){
if(!scope.a.allValues){
scope.a.allValues = "NULL";
}
ApiServices.getUser(scope.a.allValues).then(function (response){
scope.user= response.data;
});
}
我在我的文本框中调用此函数: -
<input type="text" class="form-control" ng-model="a.prod" typeahead="s for s in prods | filter:$viewValue" typeahead-on-select="fetchDetails();getUser()"/>
我想要的是先拨打fetchDetails
,它会给我allValues然后调用getUser
,这会给我剩下的数据。
但是它之后首先调用getUser
,然后调用fetchDetails
,这就是为什么我无法获取数据。如果我再次为不同的scope.a.allValues
运行该代码。它要求以前的scope.a.allValues
。
有谁能告诉我如何解决这个问题?
答案 0 :(得分:0)
它实际上首先调用fetchDetails然后调用getUser,但由于它们是异步的,因此getUser可能会在fetchDetails之前完成,反之亦然。
要使它们按顺序执行和完成,你需要链接你的promise,所以当fetchDetails()解析时,它会调用getUser()。
要做到这一点,你必须将代码更改为:
scope.fetchDetails = function(){
scope.a.data1 = scope.margin1;
scope.a.data2 = scope.margin2;
return scope.getMargin(scope.a.data1,scope.a.data2)
.then(scope.getUser);
}
scope.getMargin = function(data1,data2) {
return ApiServices.getMargin(data1,data2).then(function (response) {
scope.selected = response.data;
scope.a.allValues = scope.selected.Values;
});
}
scope.getUser = function(){
if(!scope.a.allValues){
scope.a.allValues = "NULL";
}
return ApiServices.getUser(scope.a.allValues).then(function (response){
scope.user = response.data;
});
}
然后在您看来,您只需拨打fetchDetails()
:
<input type="text" class="form-control" ng-model="a.prod" typeahead="s for s in prods | filter:$viewValue" typeahead-on-select="fetchDetails()"/>