Angular 如何在导航到其他组件时传递数据
我需要单击按钮从公司A导航到公司B,导航时我想将员工编号数据传递到公司B。由于安全问题,我不希望查询字符串URL格式(不应类似于app/structure/profile/12345) 如何通过传递数据来导航组件B 编写html代码:Angular 如何在导航到其他组件时传递数据,angular,routes,Angular,Routes,我需要单击按钮从公司A导航到公司B,导航时我想将员工编号数据传递到公司B。由于安全问题,我不希望查询字符串URL格式(不应类似于app/structure/profile/12345) 如何通过传递数据来导航组件B 编写html代码: <button class="btn btn-outline-primary " routerLink="/structure/profile">View profile</button> 但是这
<button class="btn btn-outline-primary " routerLink="/structure/profile">View profile</button>
但是这些数据在页面刷新后会消失,我想保留这些数据,所以如何在Angular中实现这一点如果您希望数据在页面刷新后出现,您应该使用
localStorage
保存它
OpenProfile(emp_no) {
localStorage.setItem('emp_no', emp_no);
this.router.navigate(['/structure/profile']);
}
然后在Comp B中从localStorage获取值
ngOnInit() {
const empNo = localStorage.getItem('emp_no');
}
您可以配置在路由定义处发送的数据:
const routes:routes=[
{
路径:“结构/配置文件”
数据:{示例:'emp_no'},
组件:ProfileComponent
}
]
当导航到“结构/配置文件”时,将发送此数据,您可以在ProfileComponent上订阅:
this.route.data.subscribe(数据=>{
this.example=数据['example'];
});
如果是动态数据,则必须创建解析程序,例如,通过一些服务调用获取数据:
@Injectable()
export class ExampleResolver implements Resolve<ExampleData> {
constructor(private exampleService: ExampleService, private router: Router) {}
resolve(route: ActivatedRouteSnapshot): Observable<ExampleData> {
return this.exampleService.getExampleData();
}
}
@Injectable()
导出类ExampleResolver实现解析{
构造函数(私有exampleService:exampleService,私有路由器:路由器){}
解析(路由:ActivatedRouteSnapshot):可观察{
返回此.exampleService.getExampleData();
}
}
同样,您必须在ProfileComponent订阅
this.route.data
。我已经尝试使用localstorage,它正在工作。。谢谢Okan Aslankani如果它对你有效,请你标记为正确答案已经完成,但由于声誉问题,投票将不会公开显示。我将尝试解决方案概念,并将结果发布回这里。谢谢你,布莱德
ngOnInit() {
const empNo = localStorage.getItem('emp_no');
}
@Injectable()
export class ExampleResolver implements Resolve<ExampleData> {
constructor(private exampleService: ExampleService, private router: Router) {}
resolve(route: ActivatedRouteSnapshot): Observable<ExampleData> {
return this.exampleService.getExampleData();
}
}