简体   繁体   中英

Communicating between two Components in Angular2

I am building an application in Angular2. I have two components, in which the second Component is loaded in the router-outlet of the first component.

Component 1
@Component({
    selector: 'component1',
    templateUrl: '
     <div>
     ...
     ...
     ...
     </div>
     <router-outlet></router-outlet>
    '
})
@RouteConfig([
    { path: '/component2', component: Component2, name: 'Component2', useAsDefault: true }])

export class Component1{
     ...
     ...
     ...
     refresh(){
        ...
        ...
     }
}

Now here is the Component2.

@Component({
        selector: 'component2',
        templateUrl: '
         <div>
         ...
         ...
         ...
         </div>
        '
    })

export class Component2{
     ...
     ...
     ...
     thisFunctionShouldRefreshComponent1(){
        //call Component1's refresh here
     }

Can someone please tell me how to call the Component1's refresh method from Component2.

Like @Jiang YD said you need a service to communicate between the components. You have to be careful where you register the provider for the service. You can either do it at the root of the application or in the top level component. So that both of the components have the same instance of the service.

Here is a simple example using observable:

// The service
@Injectable()
export class SomeService {
    refresh: Subject<boolean> = new BehaviorSubject<boolean>(false);

    refresh() { this.refresh.next(true) }
}

// Component 1
@Component({
    selector: 'c1',
    // Register the provider here for example
    providers: [SomeService]
    ...
})
export class Component1 {
   constructor(
       private _ss: SomeService
   ) {}

   refresh() {
      this._ss.refresh()
   }
}

// Component 2
@Component({
    selector: 'c2',
    ...
})
export class Component2 {
   constructor(
       private _ss: SomeService
   ) { 
       this._ss.refresh.subscribe(a => {
           if (a) this.refresh();
       })
   }  

   refresh() {
       ...
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM