簡體   English   中英

將參數推送到angularjs中的URL

[英]Push parameters to URL in angularjs

我正在制作一個angularjs應用,必須將用戶的公司名稱推送到url。 例如,www.myapp.com / samsung或www.myapp.com/toyota。

我要實現的策略是,首先檢索用戶的公司信息並獲取公司名稱,然后使用ui-router的$ stateParams將名稱推送到url。

我可以推送參數,但它不會更改url的形狀。 網址與www.myapp.com一樣。

有誰知道如何解決這個問題? 謝謝

//main controller
$rootScope.$on('$stateChangeSuccess', function (e, toState, toParams, fromState, fromParams) {
 toParams = {company: $scope.user.company.nickname};//$scope.user.company.nickname contains company's name
});

//$stateProvider configuration
$stateProvider
.$state('home', {
  url: '/:company',
  ...
  ...
})

UI-Router 1.0及更高版本可以通過onEnter Transition Hook來實現。

掛鈎檢查是否設置了參數值。 如果未設置(為null ),則將過渡重定向到相同的狀態,但設置了參數值。

  $stateProvider.state({ 
    name: 'company', 
    url: '/:companyName', 
    params: { companyName: null }, // default to null
    onEnter: function ($transition$, $state, company)  {
      let params = $transition$.params();
      if (params.companyName === null) { // check if null. Get resolve and redirect
        return $state.target("company", { companyName: company.name });
      }
    },
    resolve: { 
      company: ($http) => 
          $http.get('company.json').then(resp => resp.data)
    },
    component: 'company',
  });

這是一個工作正常的人: http ://plnkr.co/edit/aSJh6QyBUymKmaFNsOS8?p=info

如果您只需要更改URL而無需重新加載頁面,則可以使用:

var nameOfCompany = "toyota";
$location.url('/nameOfCompany');

$location是Angular的window.location等價物,可用於觀察和更改url而無需重新加載。 查看文檔以獲取更多信息。

我可以用ui-router 0.3x版本實現我想要的功能。 該代碼可能看起來很臟,但是它像我想象的那樣工作。 希望它可以幫助找到相同功能的人。

.state('home', {
    url: '/:company',
    params: {company: null},
    templateUrl: '/templates/home.html',
    onEnter: ['error', 'auth', '$state', 'company', '$stateParams', function (error, auth, $state,     company, $stateParams) {
        if (!auth.isLoggedIn()) {
            return error.flash('Login is required.', 'login');
        }
        try {
            if ($stateParams.company === null || $stateParams.company !== company.nickname) {
                $state.go('home', {company: company.nickname});    
            }
        } catch (err) {
            console.log('mop');
        }
    }],
    resolve: {
        company: ['auth', 'error', function (auth, error) {
            return auth.getMyCompany().then(function (res) {
                return res.data;
            }, function (err) {
                error.flash(401, 'login');
            });
        }],
    },
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM