angular - 角度传递值到 index.html
问题描述
我正在尝试将一个值传递给 index.html ,它调用 app.componenet。在进行重定向之前,我正在尝试处理在我的根组件中传递的查询字符串
链接目标
http://localhost:4200/index/1
HTML
<app-root></app-root>
APP.组件
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [AppComponentService]
})
export class AppComponent {
constructor(elm: ElementRef,private _service: AppComponentService, private _rout: ActivatedRoute) {
this._rout.params.subscribe(params => {
console.log('id' + params['id']);//value is undefined
});
}
应用程序路由
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
*****************************更新******************** ******************************************************
我的问题应该来自溃败..请记住,在我重定向到仪表板之前,我试图先点击 app.comonent 以执行一些逻辑
I change my rout to
const routes: Routes = [
{ path: '', component: AppComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })],
exports: [RouterModule]
})
export class AppRoutingModule { }
应用程序组件
constructor(elm: ElementRef,private _service: AppComponentService, private _rout: ActivatedRoute) {
this._rout.params.subscribe(params => {
console.log('id' + params['id']);//value is undefined
//some logic then will redirect to dashboard
});
解决方案
以下是如何根据 URL 获取 app.component.ts 中的参数。
即,http://localhost:4200/index/1
export class AppComponent {
constructor(private router: Router) {
this.router.events.subscribe( (event: RouterEvent) => {
if(event.url.startsWith('/index/')){
console.log("id is %s", event.id);
this.router.navigate(['/']);
}
});
}
}
如果要加载静态全局变量,可以使用路由数据对象传递
前任:
{ path: '', redirectTo: '/dashboard', pathMatch: 'full', data : {'one':'1', 'two': '2'} },
然后你可以得到如下的数据对象
export class AppComponent {
constructor(private router: Router) {
this.router.events.subscribe( (event: RouterEvent) => {
console.log(event['snapshot'].data)
});
}
}
推荐阅读
- ruby - rvm要求..在mac os上安装ruby卡住了
- html - 情节的标题和图例在闪亮的上下文中没有响应
- arrays - 如何修改一段 Bash 数组?
- r - 尝试绘制 R 中不同 theta 值的柯西分布的对数似然
- javascript - JavaScript 中的夏令时 (DST)
- c# - 如何对 HttpClient GetAsync 进行单元测试
- python - 名称未定义 streamlit
- java - 通过 Hibernate 在 Oracle 中的 SQL 查询中为日期传递空值
- flutter - Flutter 图像文件共享权限被拒绝
- mysql - 在 mysql 中创建事件,当数据时间列过期时更新记录