问题
I am working on this angular2 project.
I have 2 components i.e. WorkspacesComponent & PagesComponent
.
in database,each workspace contains number of pages. I have written below code to populate list of workspaces in workspacesComponent & list of pages in PagesComponent.
getting workspaces from database
this.workspaceService.getAllWorkspaces(this.baseUrl)
.subscribe((workspaces) => {
this.workspaces = workspaces;
console.log(this.workspaces);
}
);
getting pages from databases
this.pagesService.getAllpages(this.baseUrl)
.subscribe((pages) => {
this.pages = pages;
console.log(this.pages);
}
);
so far , they are returning me correct data.but I want to implement the functionality where I will be selecting workspace in workspaceComponent
& all the pages in that workspace only should be listed in pagesComponent
.
that is, on click of workspace, its index can be passed to below method.
getPagesByWorkspaceId(index:string){
console.log(index);
}
and this method will load the list of pages in that workspace accordingly.
the problem is that I am not sure how to call a method in PagesComponent
from WorkspacesComponent
any inputs?
回答1:
For communication between components that are not in a direct parent-child relationship use a shared service to share data and communicate.
For more info see https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
回答2:
If there is no relation (parent/child) between your two components, you need to leverage a shared service.
See this question for more details:
- Angular 2 - Using Observables in a component to emit values to other components
This link from the angular doc could also help you:
- https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
来源:https://stackoverflow.com/questions/37133325/angular2-how-to-communicate-between-two-separate-components