我有一个包含具有某些属性的用户的数组。当用户更改路由时,它应该只显示那些在 url 中放置了某些特定属性的人。
目前我只能显示各处的所有用户,并且当 id
更改时组件似乎没有更改。
我已经尝试过了
ngOnInit(): void {
const id = +this.route.snapshot.paramMap.get('departmentId');
this.employeeService.getEmployees()
.subscribe(emps => this.employees = emps);
this.employees = this.employees.map(emp => {
if (emp.departmentId === id) { return emp; }
});
}
最佳答案
订阅route.params
来处理更改。
然后请注意 getEmployees()
是异步的。因此,当您尝试过滤时,变量 this.employees
可能尚未初始化。您可以在订阅内进行过滤。
做类似的事情:
ngOnInit(): void {
this.route.params.subscribe(params => {
const id = +params['departmentId'];
this.employeeService.getEmployees().subscribe(emps =>
this.employees = emps.filter(emp => emp.departmentId === id)
);
}
}
关于Angular 5随着路线的改变而改变元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48354845/