How to transfer data between unrelated pages?Angular 8

I am developing an application on Angular 8. I make it multi-page, and I pass the parameters through Router. I need to transfer data from one page to another, how can I do this if my pages are not connected in any way? All pages are loaded via router-outlet.

Is it bad practice that I don't use parent.component -> child.component nesting?

Because in the future I will need to transfer data deep into the applications for my library.Example <my-library [data]="data"></my-library>

Routes

const appRoutes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'progects/:id', component: ProgectsComponent},
  { path: 'progect/:id', component: ProgectComponent},
  { path: 'polls', component: PollsComponent},
  { path: 'poll/:id', component: PollComponent},
  { path: '**', redirectTo: '/' }
];

Upvotes: 1

Views: 4092

Answers (2)

Ashot Aleqsanyan
Ashot Aleqsanyan

Reputation: 4453

You have the three ways for transfer data.

  1. Using Router.navigate()
this.router.navigate(['/polls'], {
  state: {
      data: "some data which you want"
  }
});

and get it into PollsComponent by this.router.getCurrentNavigation().extras.state but YOU NEED TO GET THE DATA INTO CONSTRUCTOR of PollsComponent, on angular lifehooks it is not exists, because it is exists until router event NavigationEnd.

  1. Using queryParams
this.router.navigate(['/polls'], {
  queryParams: {
      data: "some data which you want"
  }
});

and get it into PollsComponent by ActivatedRoute.snapshot.queryParams

  1. Using Singleton service just have a service which is providedIn: root and store it by property

But the data will lost after refresh or when user deletes the queryParams (#2 way).

Note:

I will recommend you to use params like poll/:id and get id into PollComponent onInit method and using that Id get data from. In this case, you can get :id in ActivatedRoute.snapshot.params

Upvotes: 1

Mahbub Moon
Mahbub Moon

Reputation: 511

There are a lot of ways to transfer data between different components. The choice of selection may vary based on what your goal is.

  1. Parent to child: @Input() decorator
  2. Child to parent: @Output() and EventEmitter
  3. Child to parent: @ViewChild()
  4. Unrelated component: Sharing Data as a service.

You need to create a service for sharing data between different components.

You can have a look at this article to get started.

Upvotes: 1

Related Questions