2016-06-28 31 views
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函數。

+0

你有'deferred'反模式。你可以'返回localforage.getItem('key')'得到相同的結果。 –

回答

0

您可以使用localforage.bind存儲值直接綁定到範圍:

localforage.bind($scope, {key: 'key', scopeKey: 'scKey'}); 

而且使用雙向綁定$scope.scKey

+0

我正在使用http://mozilla.github.io/localForage/這不是anuglar,肯定會嘗試你建議的。 –