如何服务404';s使用AngularJS和RESTful API
假设您有一个连接到RESTful API的AngularJS应用程序,并且有一个“/item/:itemId”的路由 如果用户转到“/item/9”,并且itemid9的对象不存在,Angular将从API接收404,但不会自然地将404返回给用户 在其他问题中,我看到有人建议创建一个拦截器,并在找不到资源时将角度重定向到404错误页面如何服务404';s使用AngularJS和RESTful API,rest,angularjs,Rest,Angularjs,假设您有一个连接到RESTful API的AngularJS应用程序,并且有一个“/item/:itemId”的路由 如果用户转到“/item/9”,并且itemid9的对象不存在,Angular将从API接收404,但不会自然地将404返回给用户 在其他问题中,我看到有人建议创建一个拦截器,并在找不到资源时将角度重定向到404错误页面 var interceptor = ['$rootScope', '$q', function(scope, $q) { ... functio
var interceptor = ['$rootScope', '$q', function(scope, $q) {
...
function error(response) {
if (response.status == 404) { window.location = '/404'; }
...
$httpProvider.responseInterceptors.push(interceptor);
然而,我想返回一个正确的404与原始请求的网址搜索引擎优化的目的
此外,上面的解决方案首先加载页面,然后重定向(就像Twitter过去所做的那样),因此是次优的
在将请求传递到Angular应用程序之前,我是否应该首先检查服务器端以查看资源是否存在?这样做的缺点是,对于应用程序中断开的链接,它不起作用
最好的方法是什么?也许这个JSFIDLE可以帮助您 我试过这个,效果很好。我只将fetch方法更改为get 在您的情况下,您需要更改
console.log('FALIURE')
到$location.path('/404')代码>
德国劳埃德船级社 首先,你是如何处理SEO的(比如对于加载的页面)?这里有一个很好的描述:我想你只需要有一个服务器端脚本,可以根据参数确定它是否是404(可能只是重定向服务器端)@shaunhusain,谢谢你的链接。我还没有投入太多的时间来处理SEO(刚刚开始),所以这应该是有帮助的。就你的建议而言,这是我考虑过的一种可能性。然而,缺点是它不适合坏的内部链接(因为它们是角度->角度的)。
var interceptor = ['$rootScope', '$q', function(scope, $q) {
...
function error(response) {
if (response.status == 404) { window.location = '/404'; }
...
$httpProvider.responseInterceptors.push(interceptor);
angular.module('dgService', ['ngResource']).factory("DriveGroup", function ($resource) {
return $resource(
'/', {}, {
update: {
method: 'PUT'
},
fetch: {
method: 'GET',
// This is what I tried.
interceptor: {
response: function (data) {
console.log('response in interceptor', data);
},
responseError: function (data) {
console.log('error in interceptor', data);
}
},
isArray: false
}
}
);
});
var app = angular.module('myApp', ['ngResource', 'dgService']);
app.controller('MainController', ['$scope', 'DriveGroup', function ($scope, svc) {
$scope.title = 'Interceptors Test';
svc.fetch(function (data) {
console.log('SUCCESS');
}, function () {
console.log('FAILURE');
});
}]);