2013-12-11 164 views
2

我有一個JSON響應:

{ 
    "success": false, 
    "error": "Server says no.", 
    "data": [] 
} 

包裹在$resource這樣的:

$resource("path-to-file.json", null, { 
    query: { 
    method: "GET", 
    isArray: false, 
    responseType: "json", 
    interceptor: { 
     response: function (response) { 
     if (!response.data.success) { 
      // stop propagation of events/promises and trigger error 
     } 
     // do something else with response.data 
     return response; 
     } 
    } 
    } 
}); 

如果"success": false我想觸發的$http誤差函數。

我想這樣做:

$scope.myVar = MyService.query(); // MyService returns $resource 
在控制器

。無論我嘗試做什麼,迴應都傳遞給$scope.myVar

+0

也許指出顯而易見的,但你意識到「inteceptor」中的拼寫錯誤吧?它應該是「攔截器」。 –

+0

@ J.P.tenBerge謝謝。拼寫更正。不幸的是這不是問題。我的實際應用程序中拼寫正確! – Simon

+0

除了Chandermani的回答,你不應該檢查'response.success'而不是'response.data.success'嗎? –

回答

1

這是值得記住的是:

的ngResource模塊提供了RESTful服務1

交互的支持。當他們說 「RESTful服務」他們意味着他們正在對端點的行爲做出一些假設。其中一個假設是成功或錯誤狀態將由HTTP狀態代碼編碼。

聽起來好像你試圖與不適合這種模式的服務交互(即你可能有一個失敗的請求返回200: OK)。如果這是你很可能直接使用$http富裕的情況下,因爲它是更普遍的:

的$ HTTP服務是核心角服務,促進與遠程HTTP服務器的通信2

由於$resource實際只是$http的包裝,我們可以通過在看看the source很容易確認的行爲(編輯爲清楚起見):

var promise = $http(httpConfig).then(function(response) { 
    var data = response.data, 
     promise = value.$promise; 

    // snip 

    value.$resolved = true; 

    response.resource = value; 

    return response; 
}, function(response) { 
    value.$resolved = true; 

    (error||noop)(response); 

    return $q.reject(response); 
}); 

promise = promise.then(
    function(response) { 
     var value = responseInterceptor(response); 
     (success||noop)(value, response.headers); 
     return value; 
    }, 
    responseErrorInterceptor); 

請記住,then()按此順序取得成功並顯示錯誤回調。你可以看到你的攔截器會被成功調用,以及主成功回調(如果有的話)。

看起來你在responseInterceptor裏面沒有任何東西可以執行錯誤回調。

我覺得你的選擇是:

  • 修改你的服務器中的行爲方式是$resource預計
  • 推出自己的$resource版本建立在$http頂部的作品,你想讓它的方式如this answer中所建議的。
1

嘗試

if (!response.data.success) { 
      return $q.reject(rejection); 
} 

看看這個調用錯誤回調。我從$httphttp://docs.angularjs.org/api/ng的文件得到了它的$ HTTP

+0

我試過/看到了。不幸的是它不起作用。在響應中拒絕[ing]不會觸發responseError(或者看起來什麼都不做)。我發現觸發responseError的唯一方法是通過HTTP響應代碼。 – Simon