Angular 2: store data while navigating between list and details

I am new to Angular 2 and now I am stuck with a new router.

Example: I have a ListComponent (/ heroes) and a DetailComponent (/ heroes /: id). The ListComponent has a filter, and depending on it, the data will be loaded into the list. When I click on an item in the list, the DetailComponent will open. When I go back to the ListComponent the filter and list are empty.

RouterConfig

const routes: Routes = [
  { path: '', redirectTo: 'heroes', pathMatch: 'full'},
  { path: 'heroes', component: HeroListComponent },
  { path: 'heroes/:id', component: HeroComponent },
  { path: '**', redirectTo: 'heroes' }
];

      

HeroListComponent.ts

import { Component, OnInit } from '@angular/core';

import { Hero } from '../shared/hero.model';
import { HeroService } from '../shared/hero.service';

@Component({
  selector: 'app-hero-list',
  templateUrl: './hero-list.component.html',
  styleUrls: ['./hero-list.component.scss'],
  providers: [HeroService]
})
export class HeroListComponent {
  filter = new Hero();
  heroes: Hero[];

  constructor(private heroService: HeroService) { }

  getHeroes(): void {
    this.heroService.getHeroes(this.filter).subscribe(heroes => {
      this.heroes = heroes;
    });
  }
}

      

HeroComponent.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

import { Hero } from '../shared/hero.model';
import { HeroService } from '../shared/hero.service';

@Component({
  selector: 'app-hero',
  templateUrl: './hero.component.html',
  styleUrls: ['./hero.component.scss'],
  providers: [HeroService]
})
export class HeroComponent implements OnInit {
  hero: Hero;

  constructor(private route: ActivatedRoute, private heroService: HeroService) { }

  ngOnInit() {
    let id = this.route.snapshot.params['id'];

    this.heroService.getHero(id).subscribe(hero => {
      this.hero = hero;
    });
  }
}

      

Is it possible to navigate between these 2 pages without losing data in the ListComponent?

I think it is possible with nested router-out, but in that case the details will be shown below the list. I want to have them on separate pages.

Or is it possible to hide the ListComponent depending on the current route so that only the DetailComponent is shown?

In Angular 1 with ui-router there was something like state.is ('heroes') and depending on what I could show / hide parts of the view.

Thank you in advance

+3


source to share





All Articles