Php angularjs路由,如何检查模板文件是否存在

Php angularjs路由,如何检查模板文件是否存在,php,angularjs,Php,Angularjs,我在我的应用程序中使用angularjs,一切都很好,但在加载模板之前,我只想检查它是否确实存在于给定的路径上 这是我的密码: .when("/:page", angularAMD.route({ templateUrl: function (rp) { return 'public/templates/' + rp.page.replace('.html', '') + '.php'; }, resolve

我在我的应用程序中使用angularjs,一切都很好,但在加载模板之前,我只想检查它是否确实存在于给定的路径上

这是我的密码:

    .when("/:page", angularAMD.route({

        templateUrl: function (rp) { 
                     return 'public/templates/' + rp.page.replace('.html', '') + '.php'; },

        resolve: {
        load: ['$q', '$rootScope', '$location', 
            function ($q, $rootScope, $location) {

                 var path = $location.path();
                 //console.log(path);
                 var parsePath = path.split("/");

                 var controllerName = parsePath[1];
                 controllerName = controllerName.replace('.html', '').replace('_', '');
                 var loadController = "public/js/controllers/" +  
                                       controllerName + "Controller.js";

                 var deferred = $q.defer();
                 require([loadController], function () {
                        $rootScope.$apply(function () {
                        deferred.resolve();
                 });
            });
            return deferred.promise;
            }]
        }

    }))
在执行此操作之前,我希望
返回'public/templates/'+rp.page.replace('.html','')+'.php';}它必须检查这个文件是否存在,否则我想重定向到404页

var checkTplUrl = function(url) {
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return (http.status !== 404) ? url : './404.html';
};
现在发生的是,当我访问某个无效链接时,我没有得到404状态,而是加载主index.html文件,因此,它开始在无限循环中运行相同的代码,最后浏览器挂起


感谢您的帮助,谢谢。

在任何非平凡的angular.js应用程序中,您都应该做一些事情,最好的地方就是定义mainmodule,然后是config块,然后是run块

 (or $scope.$on)
 $rootScope.$on("$routeChangeError", function(event, current, previous, eventObj) {
    //redirect your user to custom 404 page;
  });
如果不处理和记录那些$routeChange事件(即使用ui路由器$stateChange事件),您基本上是瞎子,会错过错误、重复路由更改和其他讨厌的事情

这里是使用ui路由器时的示例,如果使用angular basic routing,请使用angular router的Respective事件

angular.module('yourMainModuleName', ['your dependencies'])

.config(['$someProvider', function(someProvider) {
    // do setup all your global providers here
    // e.g. $http, restangular, ui-router, angular-translate....

}   ])

.run(['$rootScope', '$state', '$stateParams', 
function($rootScope, $state, $stateParams ) {

    // put ui-router $state on $rootScope, so we have access to it in all $scopes
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;

        $rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) {
            // always see what happens in your app!
            console.debug('stateChangeStart from: ' + (fromState && fromState.name) + ' to: ' + toState.name);
            // handle auth here as well, check whether user is allowed to go to this state, abort if not
            ...
        });

         $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
            // see what happens in your app!
            console.debug('stateChangeSuccess from: ' + (fromState && fromState.name) + ' to: ' + toState.name);
         });

        // log stateChangeErrors
        $rootScope.$on("$stateChangeError", function (event, toState, toParams, fromState, fromParams, error) {
            console.log('Error on StateChange from: "' + (fromState && fromState.name) + '" to:  "'+ toState.name + '", err:' + error.message + ", code: " + error.status);
            $state.go('home');
         });

}]);

创建一个服务,检查文件是否存在并返回承诺

$http.head("template2check").then(function () {
                return true;
            }, function () {
                return false;
            });
在控制器中,使用服务:

<service>.<service method>.then(function (found) {
     if (found) {......
});
。然后(函数(已找到){
如果(发现){。。。。。。
});

在ngRoute中,您需要在
config
块中配置路由,在config块中您不能使用工厂和服务,
因此您可以使用一个简单的技巧来检查模板是否存在,如果不存在,则返回404页面

var checkTplUrl = function(url) {
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return (http.status !== 404) ? url : './404.html';
};


工作示例:

那么为什么不使用$routeChangeError或notFound(某物)事件,以便更好地实现您认为将用户重定向到其他页面的内容?您能提供一些示例吗,如何使用$routeChangeError?请检查此项。我的问题是,我首先没有在路由更改上遇到错误,但不是加载模板文件,而是加载主index.html文件,并且我无法检测到任何错误d错误,我有一个解决方案,顺便说一句,向该文件发送ajax请求,然后使用该状态码怎么样?你怎么看?好还是坏。假设你访问angularjs应用程序中的无效链接。此时你不需要做任何事情。如果无效(未在路由中注册),应用程序将自动引发$routeChangeError事件(仅在未找到已注册路由时激发)。此时,对于无效链接,您不需要检查模板是否可用。仅因为$routeChangeError事件,您可以将用户重定向到自定义404页面。我希望我已经给了您明确的想法!但是我应该将此代码放在何处?在
加载:['$q'、'$rootScope'、'$location'、
部分?我已经在这里尝试过了,但没有工作,原因是即使URL无效,我也不会出错。我理解这一点,但我的问题是我的脚本不会返回错误,下面是一个示例,假设我运行这个URL
mydomain.com/hello.html
,现在脚本将返回模板文件从这个路径
public/templates/hello.html
但是这个hello.html实际上根本不存在,所以它不加载这个文件或给出错误,而是加载index.html,这是主要的应用程序文件,我们在其中包括angularjs libs和bcoz of include index.html,它在循环中加载angularjs libs,因此大量ajax调用最后浏览器崩溃了,我希望我能解释一下我的情况。当我用一个参数在常规路由中运行这个函数时,它总是返回404错误。