1

Angular で $http リクエストを作成し、方法がわからないエラー メッセージを返したいと考えています。

Express では、エラー時に次のこと (または同様のこと) を行いたいと考えています。

res.send(400, { errors: 'blah' });  

Angularでは、現在これを持っています:

$http.post('/' ,{}).then(function(res) { }, function(err) {
  console.log(err) // no errors data - only 400 error code
});

Angular内から「エラー」(つまり「何とか」)にアクセスするにはどうすればよいですか?

4

2 に答える 2

1

$http メッセージは、成功およびエラー機能を提供します。

$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

サーバーエラーや別の http エラーなど、何か問題が発生した場合、エラー関数がトリガーされ、エラーをキャッチできます。

他の何かがトリガーされる場合、またはユーザーに何らかのフィードバックを提供する必要がある場合は、success メソッドを使用できますが、データを次のような方法で返すことができます。

data {message: 'your message here', success: /*true or false*/, result: /*some data*/ }

次に、成功関数で:

$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
  if(data.success) {
     // do stuff here
  }
  else {
    // show the error or notification somewhere
  }
}).
error(function(data, status, headers, config) {
  //do stuff if error 400, 500
});
于 2013-10-26T17:35:41.373 に答える