2017-07-20 10 views
1

私は、すべてが良好で例外の場合にコントローラに応答を返すRest呼び出しを持っています。デフォルト値を返す必要があります。Angularの約束からの応答データへのアクセス

$http.get(url).then(function(res){ 
    //do some convertion on the res.data if needed 
    return res; 
}).catch(function(error){ 
    //toast the error to the user 
    return $q.when(/*default value */[]); 
}); 

コントローラからこれをアクセスすると問題が発生します。ここで私は、コントローラ変数にresponse.data値を代入していますXYZラインで

MyService.getData().then(function(response){ 
     //assign the response to the controller variable 
     vm.data = response.data; //LINE XYZ 
}); 

。問題は、例外がある場合、$q.when()は、データが直接response.dataの代わりにresponseにあるという約束を返します。

promiseを返す方法はありますか?$httpと似ていますか?

アンギュラバージョンが使用:1.6.4

答えて

0

あなたがthen関数の第二引数を使用する場合は、応答を得るでしょう。このように:

return $http.get(url).then(function(res){ 
    //do some convertion on the res.data if needed 
    return res; 
},function(res){ 
    //toast the error to the user 
    return $q.when(/*default value */[]); 
}); 

これはあなたが探しているものですか?そうしないと、あなたはあなたがこれを行うことができ、あなたのコントローラ内のデータではなく、完全な応答オブジェクトが必要な場合:

return $http.get(url).then(function(res){ 
    //do some convertion on the res.data if needed 
    return res.data; 
},function(res){ 
    //toast the error to the user 
    return $q.when(/*default value */[]); 
}); 

例外が発生した場合、あなたは文句を言わないその方法はdata -propertyを逃すあなたgetData()の結果に実行します。

関連する問題