2015-10-22 403 views
0

如果我有我的service

myServiceMethod: function(){ 
    $http.get(myUrl) 
     .success(function(result){$q.defer().resolve(result);}) 
     .error(function(error){$q.defer().resolve(error);}); 

    return $q.defer().promise; 
} 

,並在我的controller

myService.myServiceMethod() 
    .then(function(result){}) 
    .then(function(error){}); 

是有辦法在名稱空間明確?因爲如果您開始嵌套延期解析,看起來推遲的承諾可能會變得混亂。例如,

myServiceMethod: function(){ 
    $http.get(myUrl) 
     .success(
      function(result){ 
       if(result){ 
        $q.defer().resolve(result); 
       }else{ 
        $q.defer().resolve(myCustomresult); 
       } 
     }) 
     .error(function(error){$q.defer().resolve(error);}); 

    return $q.defer().promise; 
} 
+0

您是否設法解決這個問題? –

回答

0

每當你打電話給$ q.defer()時,你正在創建一個新的承諾,這是不對的。

$http.get方法本身會返回一個承諾,所以,除非你正在做別的東西,需要異步運行,你不需要使用$ Q

爲了討論各種情形,你可以這樣做:

myServiceMethod: function() { 
var myPromise = $q.defer(); 
$http.get(myUrl).success(function(result){ 
    if(result) 
     myPromise.resolve(result); 
    else 
    myPromise.reject(result); 
    }); 
return myPromise.promise; 
} 
2

你創建了太多的遞延對象和返回的人得不到你解決什麼,或者拒絕

剛剛回歸其本身會返回一個承諾的$http。你正在嘗試做被認爲是一種反模式

myServiceMethod: function(){ 
    // return the `$http` promise 
    return $http.get(myUrl) 
     .then(function(result){return result.data);}) 
     // either catch it here or catch in controller 
     .catch(function(error){ alert('Error')}); 
} 

控制器

myService.myServiceMethod() 
    .then(function(result){}) 
    .catch(function(error){}); 
0

可能是更短:

服務

myServiceMethod: function() { 
    return $http.get(myUrl).then(function (response) { 
     return response.data || myCustomResult; // default result if API returned nothing 
    }); 
} 

控制器

myService.myServiceMethod() 
    .then(function (result) { /* do something ... */ }) 
    .catch(function (error) { /* handle error ... */ });