我希望两个不同的控制器在服务中解析了一些承诺后运行不同的功能(我不希望此服务每次控制器需要数据时发出http请求,我只想要一个http请求)。承诺在多个控制器中看到的分辨率
我有一个提出请求并获得承诺的服务。我想让controller1看到这个分辨率,然后运行一些代码。然后,我想让controller2也看到这个承诺解决并运行一些代码(基本上是多个then()方法,它们在相同的承诺上运行,但是来自不同的文件)。我怎么能这样做呢?
我看到的所有示例都有一个控制器在某个承诺解决后运行代码,但不是多个控制器正在侦听相同的解决承诺。
这里是从这篇文章中的一些代码IM借款(生病添加一个“母亲控制器”来说明我的例子,我不想让儿子服务,永远做他的HTTP调用两次):http://andyshora.com/promises-angularjs-explained-as-cartoon.html
儿子服务
app.factory('SonService', function ($http, $q) {
return {
getWeather: function() {
// the $http API is based on the deferred/promise APIs exposed by the $q service
// so it returns a promise for us by default
return $http.get('http://fishing-weather-api.com/sunday/afternoon')
.then(function(response) {
if (typeof response.data === 'object') {
return response.data;
} else {
// invalid response
return $q.reject(response.data);
}
}, function(response) {
// something went wrong
return $q.reject(response.data);
});
}
};
});
父亲控制器:
// function somewhere in father-controller.js
var makePromiseWithSon = function() {
// This service's function returns a promise, but we'll deal with that shortly
SonService.getWeather()
// then() called when son gets back
.then(function(data) {
// promise fulfilled
if (data.forecast==='good') {
prepareFishingTrip();
} else {
prepareSundayRoastDinner();
}
}, function(error) {
// promise rejected, could log the error with: console.log('error', error);
prepareSundayRoastDinner();
});
};
母亲控制器:
var makePromiseWithSon = function() {
SonService.getWeather()
// then() called when son gets back
.then(function(data) {
// promise fulfilled
if (data.forecast==='good') {
workInTheGarden();
} else {
sweepTheHouse();
}
}, function(error) {
// promise rejected, could log the error with: console.log('error', error);
sweepTheHouse();
});
};
只要它在同样的情况下,你可以做出既控制器中提供的承诺参考,它不应该是太大的问题,然而,这个问题似乎模糊地承担责任? – adeneo
是的,只需创建多个使用服务中相同承诺的控制器即可。它将开箱即用。 – Bergi
@Bergi,你能看看我的编辑吗?你是说我可以让母控制器和太阳服务不会为它做一个额外的http呼叫吗?基本上是一个http请求,每个控制器在解析时都可以使用它。我关心的原因是因为请求正在执行大量查询。 –