这是我的控制器和工厂:
angular.module('app').controller('userCtrl', function($scope, User) {
$scope.users = [];
User.getUsers().then(function(response) {
$scope.users = response.data;
});
});
angular.module('app').factory('User', function($http) {
return $http.get('api-url-here').then(function(response) {
return response;
}, function(error) {
return error;
});
});
如果没有用户,后端会返回状态代码 404 ,或者如果存在内部服务器错误,则会返回状态代码 500 。否则返回状态 代码 200 和用户数组。
在我的AngularJS应用程序中,我应该如何根据状态代码显示不同的消息?我希望在不同页面中的相同状态代码上有不同的消息。
答案 0 :(得分:1)
// Defining your application module here in below.
var app = angular.module('app',['']);
// Using your application module defining your controller with dependency injection here in below.
app.controller('userCtrl',function($scope,User){
//Defining your getUser function using ECMA-5 syntax here in below.
$scope.getUser = function(){
// Using your factory named User calling the factory function getUsers().
User.getUsers().fetch({},function(respose){
if(respose.status == 200){ // using this way you could find the status of the response here.
var _data = angular.fromJson(respose.data);
$scope.users = _data;
}
}, function(respose){
$scope.users = [];
});
};
});
// Defining your factory service using your application module here in below.
app.factory('User',['$resource',$http, function($resource, $http){
var factory = {};
factoryName.getUsers = function(){
return $resource('api-url-here', {}, {
fetch: {
method: 'GET',
isArray: true,
header: {
'Content-Type' : 'application/json',
'Authorization' : Authorization
},
interceptor : {
response : function(data) {
return data;
}
}
}
})
};
return factory;
}]);