我已经将 Angular 路由设置为使用 URL 中的 slug 来确定要加载的文件。它看起来像这样:
$routeProvider.when("/project/:slug", {
controller: "ProjectController",
template: function($routeParams){
return '<div id="project" ng-include="\'/views/' + $routeParams.slug + '.html\'"></div>';
}
});
这很有用,但如果 ng-include
的文件不存在,这里就没有后备方案。我考虑过使用解析,但我似乎无法让它正确检查文件。我的尝试如下所示:
$routeProvider.when("/project/:slug", {
controller: "ProjectController",
resolve: {
check: ["$route", "$http", "$location", function($route, $http, $location){
$http.get("/views/" + $route.current.params.slug + ".html").then(function(res){
if (!res.data) $location.path("/");
else return true;
});
});
},
template: function($routeParams){
return '<div id="project" ng-include="\'/views/' + $routeParams.slug + '.html\'"></div>';
}
});
可能值得注意的是,这是 MEAN 堆栈上单页应用程序的一部分。我在 NodeJS 中设置了 Express 路由,如下所示:
app.get("*", function(req, res){ res.sendFile(__dirname + "/public/index.html"); });
最佳答案
事实证明,问题是因为我将所有文件请求路由到 NodeJS 中的 index.html。因此,当我尝试调用 $http 来检查 .html View 是否存在时,它总是返回 index.html,因此为 true。 Node中的解决方案如下:
app.use(express.static(__dirname + "/public", { maxAge: 86400000 }));
app.get("/framework/*",function(req,res){ res.sendFile(__dirname + "/public" + req.path); });
app.get("/views/*",function(req,res){ res.sendFile(__dirname + "/public" + req.path); });
app.get("*", function(req, res){ res.sendFile(__dirname + "/public/index.html"); });
然后我可以在我的 Angular 路由中使用解析,如下所示:
$routeProvider.when("/projects/:slug", {
controller: "ProjectController",
resolve: {
check: ["$route", "$http", "$location", function($route, $http, $location){
return $http.get("/views/" + $route.current.params.slug + ".html").success(function(res){
return true;
}).error(function(res){
return $location.path("/");
});
}]
},
template: function($routeParams){
return '<div id="project" ng-include="\'/views/' + $routeParams.slug + '.html\'"></div>';
}
});
所以这个问题特定于单页面应用程序设置。
关于javascript - 检查 $routeProvider 模板中是否存在 ng-include 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30868967/