3

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)

2

2 Answers 2

8

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']                             
       })
  }
Sign up to request clarification or add additional context in comments.

2 Comments

Your answer is correct but would you recommend such solution instead of using a data store / services?
Before Angular 7, I used a service. I think the only reason to use either method is which method is the most comfortable for you, but I cannot recommend one over the other.
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.