将UI路由器状态解析为没有Angular的URL

时间:2017-06-08 06:33:35

标签: javascript angularjs node.js angular-ui-router

我有一个Angular 1.5.9 Web应用程序和一个Node.js / Sails.js 0.12后端。 在Angular内部运行UI路由器0.4以处理状态。

状态定义可能看起来像这样(非常香草,我会说):

$stateProvider.state('dogs', {
            url: '/ourdogsarecute_{specialIDofDog}
        }).
        state('dogs.specialDogState', {
            url: '/specialinfo_{specialInfoOfDog}'
        });

现在,出现以下情况:在后端(即Angular之外),我必须将Angular UI路由器状态链接转换为 {stateName: 'dogs.specialDogState', stateParams: {specialIDofDog: 11212, specialInfoOfDog: 'likesbones' } }转换为有效的网址,例如https://www.our-app.dog/ourdogsarecute_11212/specialinfo_likesbones

如果没有大量的手工工作,我不知道怎么做。 UI路由器状态是否有一种解析器作为节点模块?

我可以以某种方式访问​​前端代码,其中状态定义来自后端。那不是问题。问题是从州链接转换为URL。

2 个答案:

答案 0 :(得分:1)

UI-Router 1.0将代码拆分为ui-router核心和ui-router angularjs。您可以在节点后端使用ui-router核心(没有外部依赖关系)来生成这些URL。由于您已将状态作为JSON文件提供,因此您只需在后端使用ui-router core注册状态,然后使用状态对象生成URL。

在您的节点后端,添加ui-router core

npm install --save @uirouter/core

// The library exports most of its code
var UIR = require('@uirouter/core');

// Create the router instance
var router = new UIR.UIRouter();
// Get the state registry
var registry = router.stateRegistry;

var states = [
  { name: 'dogs', url: '/ourdogsarecute_{specialIDofDog}' },
  { name: 'dogs.specialDogState', url: '/specialinfo_{specialInfoOfDog}' },
];

states.forEach(state => registry.register(state));

var params = { specialIDofDog: '11212', specialInfoOfDog: 'lovesbones' };

// Get the internal state object
var stateObj = registry.get('dogs.specialDogState').$$state();
// Generate the URL
console.log(stateObj.url.format(params));

答案 1 :(得分:0)

供参考:我的解决方案现在看起来像这样。 首先,我将我的状态定义放在一个单独的文件中,以便更容易从外部访问它:

var myStates = [
    {
        name: 'dogs', stateProperties: {
        url: '/ourdogsarecute_{specialIDofDog}'
    }
    }, {
        name: 'dogs.specialDogState', stateProperties: {
            url: '/specialinfo_{specialInfoOfDog}'
        }
    }];

然后在我的app.config

for(var i = 0; i < myStates.length; i++) {
            $stateProvider.state(myStates[i].name, myStates[i].stateProperties);
        }

在后端,我创建了这个功能:

/**
   * @description Turns state name and state params into a URL string, using stateLinks definition synchronized from front end (being UI router state definitions)
   * @param {string}  stateName Something like 'dogs.info.specialAttributes'
   * @param {object}  stateParams Something like {dogID: 34346346, dogStatus: 'private', dogInfo: 'food'}
   * @returns {string} URL
   */
  stateLinkResolve: function(stateName, stateParams) {

    if(!(stateName && stateName.length > 0)) {
      return '/';
    }

    var resultUrl = '';

    var splittedSubStates = stateName.split('.');// split "dogs.info.specialAttributes" into ["dogs","info","specialAttributes"]

    var currentStateInHierarchy = '';
    for(var i = 0; i < splittedSubStates.length; i++) {

      /* Add dot if "in between": not the first, not the last. So that "dogs" remains "dogs", but when going to "dogs.info", we want the dot in between */
      if(i > 0 && i < (splittedSubStates.length + 1) ) {
        currentStateInHierarchy += '.';
      }
      currentStateInHierarchy += splittedSubStates[i]; // Add current splitted name (being only the last name part) to the state name in its context. I.e. when doing "info", we want to access "dogs.info"
      var currState = _.find(stateDefs,{name: currentStateInHierarchy});
      var urlRaw = currState.stateProperties.url;

      /* uiRouter URLs may contain wildcards for parameter values like /ourdogs_{dogID:int}_{dogStatus}/:dogInfo.
        We go through each of these three types and replace them with their actual content.
          */
      for(var currentParam in stateParams) {
        urlRaw = urlRaw.replace(':' + currentParam, stateParams[currentParam]); // search for ":paramName" in URL
        urlRaw = urlRaw.replace('{' + currentParam + '}', stateParams[currentParam]); // search for "{paramName}" in URL

        // search for "{paramName:paramType}" in URL
        var uiRouterParamTypes = ["hash", "string", "query", "path", "int", "bool", "date", "json", "any"];
        for(var j = 0; j < uiRouterParamTypes.length; j++) {
          urlRaw = urlRaw.replace('{' + currentParam + ':' + uiRouterParamTypes[j] + '}', stateParams[currentParam]);
        }
      }
      resultUrl += urlRaw;
    }
    return resultUrl;
  }

问题是:对于边缘情况,这可能会失败,并且对于UI状态路由器实现的新功能以及在那里构建URL的方式肯定会失败。所以,仍然希望有一个直接使用UI路由器魔力的解决方案。