问题描述: 在Angular应用中,当使用懒加载加载模块时,查询参数不起作用。
解决方法:
{
path: 'lazy',
loadChildren: () => import('./lazy-module/lazy.module').then(m => m.LazyModule),
pathMatch: 'full',
canActivate: [AuthGuard],
runGuardsAndResolvers: 'always',
query: {
param1: 'value1',
param2: 'value2'
}
}
在上面的例子中,懒加载的模块为LazyModule
,并且为该模块添加了两个查询参数param1
和param2
。
ActivatedRoute
来获取查询参数。例如:import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-lazy',
templateUrl: './lazy.component.html',
styleUrls: ['./lazy.component.css']
})
export class LazyComponent implements OnInit {
param1: string;
param2: string;
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.param1 = this.route.snapshot.queryParamMap.get('param1');
this.param2 = this.route.snapshot.queryParamMap.get('param2');
}
}
在上面的例子中,通过ActivatedRoute
的queryParamMap
属性获取查询参数,并将其赋值给组件中的变量param1
和param2
。
Param 1: {{ param1 }}
Param 2: {{ param2 }}
在上面的例子中,通过双花括号语法{{}}
将查询参数显示在页面上。
通过以上步骤,就可以在懒加载的模块中获取并使用查询参数了。
上一篇:Angular懒加载一个服务