Passing value between two components (pages) in Angular 2

后端 未结 2 2036
面向向阳花
面向向阳花 2020-12-16 19:41

I am using Angular 2 (TypeScript)

I have two components (actually they are two pages too). They are NOT parent and child relationship.

I want to pass a value

2条回答
  •  生来不讨喜
    2020-12-16 20:16

    The canonical way is to establish an injectable service and inject the service into any components that need the data. Since the service is a singleton, the components will be accessing the same data. It shouldn't matter that they are on different pages. Plunker here.

    Edit: Here's a more involved example that shows two-way communication between components by subscribing to an eventEmitter on a service: Plunker

    import {Component, Injectable} from 'angular2/core'
    
    // your shared service 
    // provide reference in parent component or bootstrap 
    @Injectable()
    export class myService {
      sharedData:string = "String from myService"
    }
    
    @Component({
      selector: 'page1',
      providers: [],
      template: `
        
    Component Page1 - shared data: {{SharedData}}
    `, directives: [], }) export class Page1 { constructor(aService: myService) { this.SharedData = aService.sharedData } } @Component({ selector: 'page2', providers: [], template: `
    Component Page2 - shared data: {{SharedData}}
    `, directives: [], }) export class Page2 { constructor(aService: myService) { this.SharedData = aService.sharedData } }

提交回复
热议问题