Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 角度5随路线变化而变化的元素_Angular - Fatal编程技术网

Angular 角度5随路线变化而变化的元素

Angular 角度5随路线变化而变化的元素,angular,Angular,我有一个数组,其中包含具有某些属性的用户。当用户更改路由时,它应该只显示那些在url中具有某些特定属性的用户。 目前,我只能在任何地方显示所有用户,并且当id更改时,组件似乎不会更改 我试过这个 ngOnInit(): void { const id = +this.route.snapshot.paramMap.get('departmentId'); this.employeeService.getEmployees() .subscribe(emps =>

我有一个数组,其中包含具有某些属性的用户。当用户更改路由时,它应该只显示那些在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)
       );
    }
}

您想使用filter(),而不是map()。并且您需要在每次departmentId更改时过滤员工,而不是在组件初始化时过滤一次。因此,您需要订阅route.paramap observable,而不仅仅是查看快照。您可以扩展一下您的答案吗?您不明白什么?您是否做过一些研究,比如修改Array.map()和Array.filter()方法的文档,以了解它们的作用?阅读ActivateRoute的文档,看看route.paramMap是什么?Console抛出一个错误
属性'departmentId'在类型'Employee[]上不存在。
,认为它存在于接口中。而这个
未定义的不是对象(评估'params.get['departmentId'])
它是
参数['departmentId']
,不是
参数。获取['departmentId']
。我还更新了第一个问题的答案。现在应该没事了。在您的帮助下,我成功地从route获得了
id
,但现在它似乎无法过滤。它抛出一个错误,即类型“Observable”上不存在属性“filter”。我添加了来自
rxjs
的导入,但它会导致新的错误,这是在第一个注释中,您不应该对可观察对象进行过滤,而是对数组进行过滤。再看看我的答案。她被更新了。