How do I share data between components in Angular 2?

后端 未结 6 607
故里飘歌
故里飘歌 2020-11-22 05:04

In Angular 1.x.x you simply ask for the same service and you end up with the same instance, making it possible to share the data in the service.

Now in Angular 2 I h

6条回答
  •  日久生厌
    2020-11-22 05:33

    A service singleton is a nice solution. Other way - data/events bindings.

    Here is an example of both:

    class BazService{
      n: number = 0;
      inc(){
        this.n++;
      }
    }
    
    @Component({
      selector: 'foo'
    })
    @View({
      template: ``
    })
    class FooComponent{
      constructor(foobaz: BazService){
        this.foobaz = foobaz;
      }
    }
    
    @Component({
      selector: 'bar',
      properties: ['prop']
    })
    @View({
      template: ``
    })
    class BarComponent{
      constructor(barbaz: BazService){
        this.barbaz = barbaz;
      }
    }
    
    @Component({
        selector: 'app',
        viewInjector: [BazService]
    })
    @View({
      template: `
        
        
      `,
      directives: [FooComponent, BarComponent]
    })
    class AppComponent{}
    
    bootstrap(AppComponent);
    

    Watch live

提交回复
热议问题