Reputation: 1677
I'm doing a web application in Angular 6 and I have in a page a list of news. I have a button called "See details" and I want to take the user to another page (component) to show all the information.
// Object to pass
News {
title: string;
date: Date;
body: string;
}
// Routing
{path: 'news-details/:data', component: NewsDetailsComponent},
<ng-container *ngFor="let data of newsFromToday; index as i">
<button type="button" [routerLink]="['/news-details', data]">See details</button>
</ng-container>
In the component that I want to receive the data:
constructor(private route: ActivatedRoute) { }
ngOnInit() {
const data = this.route.snapshot.paramMap.get('data');
console.log(data);
}
Page not found
I have tried:
<button type="button" routerLink="/news-details/{{JSON.stringify(data)}}">See details</button>
ngOnInit() {
const competitionData = JSON.parse(this.route.snapshot.paramMap.get('data'));
console.log(competitionData);
}
read property 'stringify' of undefined at Object.eval [as updateDirectives]
My goal is to receive the Object in a variable to show all the information in the template.
Upvotes: 5
Views: 3041
Reputation: 4015
Solution with ActiveRoute (if you want pass object by route - use JSON.stringfy/JSON.parse):
// Routing
{path: 'news-details', component: NewsDetailsComponent}
<ng-container *ngFor="let data of newsFromToday; index as i">
<button type="button" (click)="showNewsDetails(data)">See details</button>
</ng-container>
Prepare object before sending:
constructor( private router : Router) { }
showNewsDetails(data) {
let navigationExtras: NavigationExtras = {
queryParams: {
"data": JSON.stringify(data)
}
};
this.router.navigate(["news-details"], navigationExtras);
}
Receive your object in destination component:
constructor( private route: ActivatedRoute) {}
ngOnInit(): void {
super.ngOnInit();
this.route.queryParams.subscribe(params => {
const data = = JSON.parse(params["data"]);
});
}
note that if you do not want to expose all data in the URL, using a service is the way to go. In route params you should only pass data that you want to be reflected in the browser URL bar.
Upvotes: 3