2014-11-25 41 views
0

我現在需要返回承諾,否則服務器http請求會返回該承諾,我需要拒絕承諾,所以我不必不必要地打到服務器。我一直在試圖使並返回一個拒絕承諾,是這樣的:

var promise = $q.defer().promise; 
return promise.reject(value); // doesn't work 

return $q.reject(); // also doesn't work 

我似乎無法弄清楚是怎麼回事拒絕承諾,這樣我就可以節省服務器調用,但是我處在一個地方,它要麼返回一個被拒絕的承諾,要麼進行服務器調用。我介於兩者之間,我沒有在原來的調用該調用的子指令,並且孩子無法進行父指令中可能的比較。反正有沒有$超時這樣做?

回答

2

我想你正在尋找的是

var app = angular.module('my-app', [], function() { 
 

 
}) 
 

 
app.controller('AppController', ['$scope', '$q', 
 
    function($scope, $q) { 
 
    $scope.message = 'This is for testing'; 
 

 
    function test() { 
 
     //create a deferred object 
 
     var deferred = $q.defer(); 
 
     //reject the promise 
 
     deferred.reject(2); 
 
     //then return the promise 
 
     return deferred.promise; 
 
    } 
 

 
    test().then(function() { 
 
     $scope.message = 'Resolved'; 
 
    }, function() { 
 
     $scope.message = 'Rejected'; 
 
    }) 
 
    } 
 
])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="my-app" ng-controller="AppController"> 
 
    {{message}} 
 
</div>

deffered api有拒絕/解決方法,在這裏爲promise api已用於註冊的回調方法方法

+0

啊,我明白我做錯了什麼。非常感謝 – mtpultz 2014-11-25 02:31:35