业务需求:一个页面中需包含多个子模块页面(功能独立),要控制每个模块数据的请求都在上一个模块response后才触发。
思路:
1、初期考虑把子模块放一起,通过调用对应方法实现,但如果后期要拆分成不同菜单页面,很是麻烦(是的,拆过)。
2、在父模块做监听 $on,当子模块一请求完数据后,$emit通知父模块,通过$broadcast触发子模块二请求数据,以此类推、、、
父模块:
class ParentComponent {
constructor($scope) {
$scope.$on('sendToParent', function(event, data) {
if (data.formChildOne)
$scope.$broadcast('sendToChildSecond', { load: true });
else if (data.formChildSecond)
$scope.$broadcast('sendToChildThird', { load: true });
});
}
}
子模块一:
class ChildOneComponent {
constructor($scope,$http) {
this.$scope = $scope;
this.$http = $http;
this.dataSearch()
.then(() => {
$scope.$emit('sendToParent', { formChildOne: true });
});
}
dataSearch() {
var ta = this;
ta.loading = true;
return new Promise((resolve, reject) => {
ta.$http({
method: "POST",
url: "test1",
data:{},
timeout: 6000,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
})
.then((res) => {
ta.loading = false;
})
.catch((err) => {
ta.loading = false;
failCb(err.data);
})
.finally(() => {
resolve();
});
});
}
子模块二:
class ChildSecondComponent {
constructor($scope, $http) {
this.$scope = $scope;
this.$http = $http;
$scope.$on('sendToChildSecond', (event, data) => {
if (data.load) {
this.dataSearch()
.then(() => {
$scope.$emit('sendToParent', { formChildSecond: true });
});
}
});
}
dataSearch() {
var ta = this;
ta.loading = true;
return new Promise((resolve, reject) => {
ta.$http({
method: "POST",
url: "test2",
data: {},
timeout: 6000,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
})
.then((res) => {
ta.loading = false;
var data = res.data;
if (data.resultCode === 0) {
ta.dataList = data.data;
} else {
throw res;
}
})
.catch((err) => {
ta.loading = false;
failCb(err.data);
})
.finally(() => {
resolve();
});
});
}