Angular 2/4 如何获取app组件中的路由参数?

Angular 2/4 How to get route parameters in app component?

因为我是 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']; 
    });
  }

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

提前致谢!

因为图像参数对象什么都没有。

这个 post 解决了问题。

我需要创建一个单独的组件 Root 并且我保留了我的 Router-Outlet 并将该组件添加为我的 bootstrap 模块并且它工作了!我的声望不会超过 50,如果我有的话我会感谢他 post。谢谢@Fabio Antunes

一次值使用如下:

import { Router  , ActivatedRoute } from '@angular/router';

constructor(private route: ActivatedRoute){}
ngOnInit() {
    console.log(this.route.snapshot.params['username']);
}

以上快照方法。快照方法只会在您启动组件后为您提供结果。因此,如果您更改路线或销毁组件并再次启动,它将继续工作。

反对者的解决方案and/or任何想要在每次路由更改时更新参数的人将是:

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'])});
}
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);
        }
    });

}

}

我的应用程序需要读取 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
        ));
}