Ui-router: conversion parameter from url

Is it possible to transparently convert URL parameters? How hard it is to explain, I will give a script. We have a URL structure like this:

/shopping/nuts/:productId
/shopping/berries/:productId
/shopping/juice/:productId

Our products shown in the app (supplied by some APIs) might look something like this:

{ type: 'berry', price: 123, text: 'lorem ipsum', id: '12345' }

Note the mismatch between singular and plural: the URL contains the plural, for example. "berries", while the products supplied by our REST API use a special form of "berry".

Part of our state definition looks something like this:

.state('shop.product', {
  url: '/shopping/:type/:productId',
  templateUrl: 'type.html',
  controller: 'TypeController'
})

: $state (toSingular($stateParams.type)), . .

, -

URL /shopping/berries/12345 $stateParams.type === 'berry', URL- ui-sref="shop.product({type: 'berry', id: '12345'})" URL /shopping/berries/12345.

, , . !

+4
2

.

https://ui-router.imtqy.com/docs/latest/classes/url.urlmatcherfactory.html#type

URL-.

encode (nut, berry ..) , URL-.

decode URL- .

 var productTypes = {
    berry: ['berries', 'berry'],
    nut: ['nuts', 'nut'],
    juice: ['juice'],
  }

  $urlMatcherFactoryProvider.type('productType', {
    encode: val => 
      productTypes[val][0],
    decode: string =>
      Object.keys(productTypes).find(key => productTypes[key].indexOf(string) !== -1),
  });

, : http://plnkr.co/edit/Eed8h7U6x0j8RAWs7qT9?p=preview

+2

:

URL /shopping/berries/12345 , stateParams.type. Beacause, type, URL- shopping/berry/12345. url shop.product({type: 'x', id: '12'}), URL shopping/x/12. , stateParams URL. , URL-, . . $urlRouterProvider.otherwise(), .

$stateProvider.state('shop', {
  url: 'shopping'
})
.state('shop.product', {
  url: '/:type/:id'
});
$urlRouterProvider.otherwise('/');

URL-, '/'

0

Source: https://habr.com/ru/post/1662882/


All Articles