Angular 2/4 如何在应用程序组件中获取路由参数? [英] Angular 2/4 How to get route parameters in app component?
问题描述
由于我是 angular 2/4 的新手,因此无法根据需要设置新应用程序.
As I am new to angular 2/4 I am having trouble setting up a new application as per my need.
我正在尝试构建一个将从其他应用程序调用的应用程序.调用应用程序将发送一些参数,如令牌、用户名、应用程序 ID 等.
I am trying to build an application which will be called for from some another application. Calling application will send some parameter like token, username, application id and etc.
现在,就像在 Angular 2/4 中一样,app.component 是我们的着陆组件,每个第一个请求都会通过它.所以,我想在应用组件中获取这些参数并加载一些用户详细信息,进行本地会话并转移到其他内容.
Now, as in Angular 2/4, app.component is our landing component and every first request will go through it. So, I want to get those parameter here in app component and load some user detail, make a local session and the move to other stuff.
问题是当我试图访问这些参数时,我得到了任何东西.
problem is when I am trying to access these parameter I am getting anything.
这是将启动我的 angular 应用程序的 URL:http://localhost:86/dashboard?username=admin&token=xyz&appId=8
Here is the URL which will start my angular application: http://localhost:86/dashboard?username=admin&token=xyz&appId=8
这是我的路由文件代码:
Here is my routing file code:
const routes: Routes = [
{
path: 'dashboard/:username, token', component: AppComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
这是我的应用组件代码:
Here is my App Component Code:
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'];
});
}
这里的参数是空的,不知道为什么?
Here params is empty don't know why?
提前致谢!
因为在图像参数对象中什么都没有.
As in image params object has nothing.
推荐答案
这篇文章解决了问题.这里
我需要创建一个单独的组件 Root 并且我保留了我的 Router-Outlet 并将这个组件添加为我的引导模块并且它工作了!!如果我有的话,我的声誉不会超过 50,我会在同一个帖子上感谢他.谢谢@Fabio Antunes
I needed to create a separate component Root and in that i kept my Router-Outlet and added this component as my bootstrap module and it worked!! I do not have reputation more than 50 if i had than i would thanked him on the same post. Thanks man @Fabio Antunes
这篇关于Angular 2/4 如何在应用程序组件中获取路由参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!