【问题标题】:Angular 2/4 How to get route parameters in app component?Angular 2/4 如何在应用程序组件中获取路由参数?
【发布时间】:2017-12-31 17:22:56
【问题描述】:

由于我是 angular 2/4 新手,我无法根据需要设置新应用程序。

我正在尝试构建一个将从其他应用程序调用的应用程序。调用应用程序将发送一些参数,如令牌、用户名、应用程序 ID 等。

现在,就像在 Angular 2/4 中一样,app.component 是我们的登陆组件,每个第一个请求都将通过它。所以,我想在应用程序组件中获取这些参数并加载一些用户详细信息,进行本地会话并转移到其他内容。

问题是当我尝试访问这些参数时,我得到了任何东西。

这是启动我的 Angular 应用程序的 URL: http://localhost:86/dashboard?username=admin&token=xyz&appId=8

这是我的路由文件代码:

const routes: Routes = [
  {
    path: 'dashboard/:username, token', component: AppComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {

}

这是我的应用组件代码:

import { Component, OnInit } from '@angular/core';
import { AuthenticationService } from 'app/services/authentication/authentication.service';
import { User } from 'app/models/user/user';
import { AppConfig } from 'app/helpers/AppConfig';
import { ActivatedRoute, Router } from '@angular/router';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  _user: User = new User();
  obj: any;
  error: any;

  loginName: string;
  private id: any;

  constructor(
    private authenticationService: AuthenticationService,
    private config: AppConfig,
    private route: ActivatedRoute,
    private router: Router

  ) { }

  ngOnInit() {    
    this.loadCurrentUserDetail();
    this.getParamValues()

  }

  getParamValues() {
    this.id = this.route.queryParams.subscribe(params => {      
       this.loginName = params['username']; 
    });
  }

这里的参数是空的不知道为什么?

提前致谢!

在图像参数对象中什么都没有。

【问题讨论】:

    标签: angular angular2-routing


    【解决方案1】:

    这篇文章解决了问题。 here

    我需要创建一个单独的组件 Root 并且我保留了我的 Router-Outlet 并将这个组件添加为我的引导模块并且它有效!如果我有超过 50 的声誉,我会在同一个职位上感谢他。谢谢@Fabio Antunes

    【讨论】:

      【解决方案2】:

      一次性价值使用如下:

      import { Router  , ActivatedRoute } from '@angular/router';
      
      constructor(private route: ActivatedRoute){}
      ngOnInit() {
          console.log(this.route.snapshot.params['username']);
      }
      

      上面的快照方法。启动组件后,快照方法只会为您提供结果。因此,如果您更改路线或销毁组件并仅重新启动,这将继续工作。

      针对投票者和/或任何想要在每次路线更改时更新参数的人的解决方案将是:

      import { Router  , ActivatedRoute } from '@angular/router';
      
      constructor(private route: ActivatedRoute){}
      ngOnInit() {
          // Works first time only
          console.log(this.route.snapshot.params['username']);
          // For later use, updates everytime you change route
          this.route.params.subscribe((params) => {console.log(params['username'])});
      }
      

      【讨论】:

      • 为什么这个答案被否决了?在当前的 Angular 版本 (6) 中,这是一个干净的好工作解决方案。
      • 人们有理由讨厌最好的,而且这只是另一个答案
      • 很好的解决方案。我使用替代版本直接使用“this.route.params”获取 ngOnInit 上的值,而不使用“快照”。有谁知道有什么区别?
      • 否决票是因为问题是针对应用程序组件的。应用组件是非路由的,因此无法通过激活的路由获取参数。
      • 但它会是空的,我第一次打开应用程序时,这将我们带入原始问题如何解决“空参数”问题。 app.component.ts 没有路由,因此对使用的参数一无所知。如果我有像:username/:token/:whatever 这样的路线,它将无法映射param.usernameparam.tokenparam.whatever
      【解决方案3】:
      import { Component, OnInit, OnDestroy } from '@angular/core';
      import {  Router, ActivatedRoute, Params, RoutesRecognized  } from '@angular/router';
      
      @Component({
        selector: 'app-root',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.scss']
      })
      export class AppComponent implements OnInit {
      
        constructor( private route: ActivatedRoute, private router: Router ) {}
      
        ngOnInit(): void {
          this.router.events.subscribe(val => {
             if (val instanceof RoutesRecognized) {
               if (val.state.root.firstChild.params.id) {
                localStorage.setItem('key1', val.state.root.firstChild.params.id);
                localStorage.setItem('key2', val.state.root.firstChild.params.id2);
               }
                  console.log('test', val.state.root.firstChild.params);
              }
          });
      
      }
      
      }
      

      【讨论】:

        【解决方案4】:

        我的应用程序需要读取 appComponent(未路由)中的 queryParams,以便能够在路由到任何其他组件之前设置一些变量。 我不想改变架构来路由 appComponent。

        这是我订阅路由器事件的方法:

        private _queryParamsSet: boolean = false;
          constructor(
            private _router: Router,
            private _activatedRoute: ActivatedRoute
          ) { }
        
          async ngOnInit() {    
             const onNavigationEnd = this._router.events
              .pipe(
                tap((data) => {
                  if (!this._queryParamsSet && (data as NavigationStart)?.url) {
                    const queryParams = CoreHelper.getQueryParamsFromURL((data as 
                       NavigationStart).url);
                    if (queryParams) {
                      // set variables which will eventually decide which route to take
                    }
                    this._queryParamsSet = true;
                  }
                }),
                filter(
                  event => event instanceof NavigationEnd
                ));
        }
        

        【讨论】:

          猜你喜欢
          • 2017-09-16
          • 1970-01-01
          • 2017-06-12
          • 2016-11-25
          • 1970-01-01
          • 2016-10-28
          • 2017-07-16
          • 2018-06-12
          • 2020-04-24
          相关资源
          最近更新 更多