如何在Angular 2中的组件之间共享数据?

时间:2015-06-24 12:41:10

标签: angular typescript

在Angular 1.x.x中,您只需要提供相同的服务即可获得相同的实例,从而可以在服务中共享数据。

现在在Angular 2中我有一个引用我的服务的组件。我可以阅读和修改服务中的数据,这很好。当我尝试在另一个组件中注入相同的服务时,似乎我得到了一个新实例。

我做错了什么?是模式本身是错误的(使用服务来共享数据)还是我需要将服务标记为单例(在应用程序的一个实例中)或什么?

我在2.0.0-alpha.27/ btw

我通过appInjector(编辑:现在providers)在@Component注释中注入服务,然后在构造函数中保存引用。它在组件本地工作 - 只是不跨组件(它们不共享相同的服务实例),就像我想的那样。

更新:从Angular 2.0.0开始,我们现在有了@ngModule,您可以在providers上的@ngModule属性下定义服务。这将确保将该服务的相同实例传递给该模块中的每个组件,服务等。 https://angular.io/docs/ts/latest/guide/ngmodule.html#providers

6 个答案:

答案 0 :(得分:56)

服务单身人士是一个不错的解决方案。其他方式 - data/events bindings

这是两个例子:

class BazService{
  n: number = 0;
  inc(){
    this.n++;
  }
}

@Component({
  selector: 'foo'
})
@View({
  template: `<button (click)="foobaz.inc()">Foo {{ foobaz.n }}</button>`
})
class FooComponent{
  constructor(foobaz: BazService){
    this.foobaz = foobaz;
  }
}

@Component({
  selector: 'bar',
  properties: ['prop']
})
@View({
  template: `<button (click)="barbaz.inc()">Bar {{ barbaz.n }}, Foo {{ prop.foobaz.n }}</button>`
})
class BarComponent{
  constructor(barbaz: BazService){
    this.barbaz = barbaz;
  }
}

@Component({
    selector: 'app',
    viewInjector: [BazService]
})
@View({
  template: `
    <foo #f></foo>
    <bar [prop]="f"></bar>
  `,
  directives: [FooComponent, BarComponent]
})
class AppComponent{}

bootstrap(AppComponent);

Watch live

答案 1 :(得分:43)

@maufarinelli的评论应该得到自己的答案,因为在我看到它之前,即使用@Alexander Ermolov的答案,我仍然仍然用这个问题抨击我的头。

问题是,当您向providers添加component

@Component({
    selector: 'my-selector',
    providers: [MyService],
    template: `<div>stuff</div>`
})

这会导致您的服务的新实例被注入...而不是 singleton

因此,除了providers: [MyService]之外,删除应用中module的所有实例,它都会有效!

答案 2 :(得分:9)

您必须使用@Component装饰器的输入和输出。以下是使用两者的最基本示例;

import { bootstrap } from 'angular2/platform/browser';
import { Component, EventEmitter } from 'angular2/core';
import { NgFor } from 'angular2/common';

@Component({
  selector: 'sub-component',
  inputs: ['items'],
  outputs: ['onItemSelected'],
  directives: [NgFor],
  template: `
    <div class="item" *ngFor="#item of items; #i = index">
      <span>{{ item }}</span>
      <button type="button" (click)="select(i)">Select</button>
    </div>
  `
})

class SubComponent {
  onItemSelected: EventEmitter<string>;
  items: string[];

  constructor() {
    this.onItemSelected = new EventEmitter();
  }

  select(i) {
    this.onItemSelected.emit(this.items[i]);
  }
}

@Component({
  selector: 'app',
  directives: [SubComponent],
  template: `
    <div>
      <sub-component [items]="items" (onItemSelected)="itemSelected($event)">
      </sub-component>
    </div>
  `
})

class App {
  items: string[];

  constructor() {
    this.items = ['item1', 'item2', 'item3'];
  }

  itemSelected(item: string): void {
    console.log('Selected item:', item);
  }
}

bootstrap(App);

答案 3 :(得分:6)

在父组件模板中:

<hero-child [hero]="hero">
</hero-child>

在子组件中:

@Input() hero: Hero;
  

来源:https://angular.io/docs/ts/latest/cookbook/component-communication.html

答案 4 :(得分:2)

有很多方法。这是使用父元素和子元素之间传播的示例。这非常有效。

我提交了一个示例,允许在两种形式中查看两种数据绑定方式的用法。如果有人可以提供一个plunkr样本,这将是非常好的; - )

您可以使用服务提供商寻找其他方式。 您也可以查看此视频以供参考: ( Sharing Data between Components in Angular

mymodel.ts(要分享的数据)

// Some data we want to share against multiple components ...
export class mymodel {
    public data1: number;
    public data2: number;
    constructor(
    ) {
        this.data1 = 8;
        this.data2 = 45;
    }
}

请记住:必须有一位父母将分享&#34; mymodel&#34;儿童组成部分。

父组件

import { Component, OnInit } from '@angular/core';
import { mymodel } from './mymodel';
@Component({
    selector: 'app-view',
    template: '<!-- [model]="model" indicates you share model to the child component -->
        <app-mychild [model]="model" >
        </app-mychild>'

        <!-- I add another form component in my view,
         you will see two ways databinding is working :-) -->
        <app-mychild [model]="model" >
        </app-mychild>',
})

export class MainComponent implements OnInit {
    public model: mymodel;
    constructor() {
        this.model = new mymodel();
    }
    ngOnInit() {
    }
}

子组件mychild.component.ts

import { Component, OnInit,Input } from '@angular/core';
import { FormsModule }   from '@angular/forms'; // <-- NgModel lives here
import { mymodel } from './mymodel';

@Component({
    selector: 'app-mychild',
    template: '
        <form #myForm="ngForm">
            <label>data1</label>
            <input type="number"  class="form-control" required id="data1 [(ngModel)]="model.data1" name="data1">
            <label>val {{model.data1}}</label>

            label>data2</label>
            <input  id="data2"  class="form-control" required [(ngModel)]="model.data2" name="data2" #data2="ngModel">
            <div [hidden]="data2.valid || data2.pristine"
                class="alert alert-danger">
                data2 is required
            </div>

            <label>val2 {{model.data2}}</label>
        </form>
    ',
})

export class MychildComponent implements OnInit {
    @Input() model: mymodel ;  // Here keywork @Input() is very important it indicates that model is an input for child component
    constructor() {
    }
    ngOnInit() {
    }
}

注意:在极少数情况下,解析HTML代码时可能会出错,因为模型不准备好&#34;在页面初始化时使用。在这种情况下,在HTML代码前加上ngIf条件:

<div *ngIf="model"> {{model.data1}} </div>

答案 5 :(得分:0)

要视情况是否简单

a)A-> B      -> C A有两个孩子B和C,如果要在A和B或A和C之间共享数据,请使用(输入/输出)

如果您想在B和C之间共享,那么您也可以使用(输入/输出),但建议使用Service。

b)如果树又大又复杂。 (如果有很多级别的父级和子级连接。) 在这种情况下,如果您要共享数据,那么我建议ngrx

它实现了流量体系结构,该体系结构创建了一个客户端存储,任何组件都可以订阅并更新该客户端存储,而无需创建任何竞争条件。