Reputation: 77
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
Reputation: 4453
You have the three ways for transfer data.
- 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
.
- Using queryParams
this.router.navigate(['/polls'], {
queryParams: {
data: "some data which you want"
}
});
and get it into PollsComponent by ActivatedRoute.snapshot.queryParams
- 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).
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
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.
@Input()
decorator@Output()
and EventEmitter
@ViewChild()
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