在Angularjs中,ui-router访问状态url开头的参数

angularjs, ui-router access to parameter at the beginning in the state url

本文关键字:url 开头 参数 状态 访问 Angularjs ui-router      更新时间:2023-09-26

我有一个完全用HTML5/JavaScript编写的前端web应用程序,MVC由AngularJS框架使用UI-Router进行管理。

现在…我需要使用以下模式使用单个应用程序管理更多客户:

  • 所有客户都有一个applicationName (System.String)
  • 要访问到应用程序的url是[domain]/:applicationName/[view state],如:http://domain.com/MyName/login或http://domain.com/MyName/home/dashboard
在Angular引导文件的config函数中,我必须这样做:
 .state('home.dashboard', {
     url: '/:applicationName/home/dashboard',
     templateUrl: '/views/contents/dashboard.html'
  });

所以问题是:applicationName是检索存储在数据库中的对应applicationId (System.Guid)的唯一名称(此applicationId用于从数据库检索对应applicationName数据,因此用于所有请求)。

那么问题来了:在解析状态url之前,我能不能检索到applicationName,然后向rest api请求获取对应的applicationId,并将其存储在angular服务中?

是可能的吗?如果是,我该怎么做?

非常感谢大家!

洛伦佐

我认为你应该在app运行函数中使用$locationChangeStart事件,在那里你可以从数据库(使用service/provider)中获取应用程序名称。

        app.run(["$rootScope", "$location", "$window",function ($rootScope, $location, $window){
             $rootScope.$on("$locationChangeStart", function (event, next, current) {
                 alert($location.$$path);
             });
        }])

这可以通过多种方式实现。不过我有个建议,

  1. 有默认路由,写控制器
  2. 在控制器内部,请确保调用API并获得应用程序id
  3. 在控制器中你可以执行$state.go()看到的:https://github.com/angular-ui/ui-router/wiki/URL-Routing using-parameters-without-specifying-them-in-state-urls