无法获得在使用其他组件数据导航在角2

无法获得在使用其他组件数据导航在角2

问题描述:

**Current Code:**: 

Currently i working at filter component. I have data, getting from service and i have successfully navigate to user component.无法获得在使用其他组件数据导航在角2

**My Code is**`getFilterDetails(){ 
this.userService.getFilterDetailsDetails(this.locations).subscribe(data => { 
    this.filterType = data; 
    }); 
this.router.navigate(['user']); 
}` 
*Problem is i need to pass data to user component and how to get data in user component. Kindly help me to get this done?* 

您可以使用您在这两个组件注入共享的服务。

@Injectable() 
export class sharedService { 
data: any; 
} 

并在第一个组件,这样做:

this.userService.getFilterDetailsDetails(this.locations).subscribe(data => { 
    this.filterType = data; 
this.sharedService.data = data; 
this.router.navigate(['user']); 
    }); 
} 

,并在其他部分,注射服务,并使用这些数据。

+0

我使用像下面getFilterDetails(){ this.userService .getFilterDetailsDetails(this.locations).subscribe(data => {this.filterType = data; this.userService.sa veFilterData(this.filterType); }); this.router.navigate(['user']);.但我得到的错误“ExpressionChangedAfterItHasBeenCheckedError:检查后表达式已更改前一个值:'true'。当前值:'false'”和在用户组件中我使用下面的代码来获取数据“this.flterData = this .userService.retrieveFilterData();” –

+0

您是否正在执行'AfterViewInit'阶段中的组件属性更改? –

+0

没有Radouane。我是否应该包含任何“ActivatedRoute”或是否包含任何模块?请帮助我 –

可以传递数据:

this.router.navigate(['user'], { data: { yourData : yourData } }); 

和检索数据

constructor(private route: ActivatedRoute) {} 
ngOnInit() { 
    this.route 
     .data 
     .subscribe(data=> { 
     this.data= data || {}; 
     }); 
} 

希望这有助于:)

+0

能否请你告诉我,我该怎么以下路由器出口常量appRoutes任何变化:路线= [ { 路径:“用户”, 组件:UserComponent }]。 –

+0

不需要做任何改变。你可以直接做到这一点。 – SaiUnique