Reputation: 51
I have an "home" component where I iterate my mangas (mangas is an array of objects)
like this:
<div *ngFor="let manga of mangas">
<h1> {{ manga.title }} </h1>
<button routerLink="/manga/{{ manga.title }}"> read the manga </button>
</div>
(it's better than this but it's just to make an example)
so, how can I pass the entire "manga" object to the new route?
(i don't wanna to pass the entire array)
Upvotes: 3
Views: 11013
Reputation: 58114
if you want to pass an object to a router (not a simple parameter), you use "states" take a look this links
<div *ngFor="let manga of mangas">
<a routerLink="/manga" [state]="manga">
</div>
And get it in OnInit. Normally, if you use state to get an object, you usually want that, if no object, router to "home", If your object manga has a property, mangaId
you can use this information inside the subscription
constructor(public activatedRoute: ActivatedRoute) {}
ngOnInit() {
this.activatedRoute.paramMap
.pipe(map(() => window.history.state)).subscribe(res=>{
console.log(res) //<--see thah you has an additional property:navigationId
//you can check if you has passed an object really
//If, e.g. your manga has a property mangaId<>0
if (!res.mangaId)
router.navigate(['/home']
})
}
Upvotes: 7
Reputation: 12837
You should not be passing the object itself in the route but rather the ID of the object and then retrieving the object from some type of datastore.
<div *ngFor="let manga of mangas">
<h1> {{ manga.title }} </h1>
<button routerLink="/manga/{{ manga.id }}">
read the manga
</button>
</div>
In the spirit of a single page application, you might want to have a manga service (repository) that manages the collection of mangas.
Upvotes: 4