Reputation: 857
I have a problem with passing data to other component. Here is the example.
onEdit(data) {
this.router.navigate(["/edit", { state: data }], {
relativeTo: this.activatedRoute
});
}
And my router ts
file:
{
path: "edit",
component: ServiceTimeGoalUpdateComponent,
resolve: {
serviceTimeGoal: ServiceTimeGoalResolve
},
data: {
pageTitle: "ServiceTimeGoals",
data: "data"
}
},
What i exactly want is when i click to edit button from the list it should be navigate to edit
and with some data. What am i doing wrong ?
Upvotes: 1
Views: 640
Reputation: 57939
@batgerel, You has an error in your code. must be
this.router.navigate(['./edit'],
{ relativeTo: this.activatedRoute, state: { data } })
And, if your component it's not the main app, in ngOnInit
this.activatedRoute.paramMap.pipe(
take(1), //take(1) is for unsubscribe
map(() => window.history.state)
).subscribe(res => {
console.log(res.data)
})
Upvotes: 1
Reputation: 6016
I think you need to change your routing to something like below,
you can use QueryParams for your scenario
this.router.navigate(["/edit"], {
queryParams: { dataParam : value, dataPara2: value }
});
get the value by subscribing to ActivatedRoute
in Component.
this.route.queryParams.subscribe(params => {
console.log(params['dataParam '],params['dataPara2']);
});
you can also remove the data
param in Routing initialization.
Edit
If you have already a common service use that otherwise create service class like below,
export class ServiceName {
private data = new BehaviorSubject<any>([]);
getData(): Observable<any> {
return this.data.asObservable();
}
setData(param: any): void {
this.data.next(param);
}
}
then you can call the data
methods in component before navigating the router, and get the data with getData()
method.
this.service.setData(data);
this.router.navigate(["/edit", { state: data }], {
relativeTo: this.activatedRoute
});
Hope this helps.. :)
Upvotes: 1