1
angularjs用watchExpression返回承諾的watch方法。
$scope.$watch(function() {
var promise = MyService.getMethod();
promise.then(function(value){
return value;
})
}, function(newValue, oldValue) {
console.log("new value:", newValue);
});
帶有承諾的方法的打字稿調用。
public getMethod(): angular.IPromise<any> {
var deferred: angular.IDeferred<any> = this.$q.defer();
localforage.getItem(‘key’).then(function(value) {
deferred.resolve(value);
}).catch(function(err) {
deferred.reject();
console.log(err);
});
return deferred.promise;
}
我想從MyService中的localforage承諾返回「value」以返回到$ watch watchExpression函數。
你有'deferred'反模式。你可以'返回localforage.getItem('key')'得到相同的結果。 –