Angular2:将数据从一个组件发送到另一个组件并使用数据

时间:2016-05-28 13:22:38

标签: javascript angular

我正在学习Angular2。为此,我有2个组件,在点击其中一个组件时,应该通知另一个组件并采取相应的行动。

到目前为止,这是我的代码:

export class JsonTextInput {
  @Output() renderNewJson: EventEmitter<Object> = new EventEmitter()
  json: string = '';

  process () {
      this.renderNewJson.next(this.json)
  }
}

在点击第一个组件时调用过程函数。 在第二个组件上,我有这个代码:

export class JsonRendered {
  @Input() jsonObject: Object

  ngOnChanges () {
    console.log(1)
    console.log(this.jsonObject)
  }
}

ngOnChanges永远不会运行,我不知道如何将信息从一个组件传递给其他组件

修改

有一个app组件,它是这两个组件的父组件。两者都不是另一个的父母

这就是我的clasess现在的样子:

export class JsonRendered {
  private jsonObject: Object

  constructor (private jsonChangeService: JsonChangeService) {
    this.jsonChangeService = jsonChangeService
    this.jsonObject = jsonChangeService.jsonObject
    jsonChangeService.stateChange.subscribe(json => { this.jsonObject = json; console.log('Change made!') })
  }
}


export class JsonTextInput {
  json: string = '';

  constructor (private jsonChangeService: JsonChangeService) {
    this.jsonChangeService = jsonChangeService
  }

  process () {
    this.jsonChangeService.jsonChange(this.json)
  }
}

服务

import {Injectable, EventEmitter} from '@angular/core';
@Injectable()
export default class JsonChangeService {
  public jsonObject: Object;

  stateChange: EventEmitter<Object> = new EventEmitter<Object>();

  constructor(){
    this.jsonObject = {};
  }

  jsonChange(obj) {
    console.log('sending', obj)
    this.jsonObject = obj
    this.stateChange.next(this.jsonObject)
  }

}

1 个答案:

答案 0 :(得分:1)

创建一个像这样的服务......

    import {Injectable, EventEmitter} from 'angular2/core';
@Injectable()
export class MyService {

  private searchParams: string[];

  stateChange: EventEmitter<any> = new EventEmitter<any>();

  constructor(){

    this.searchParams = [{}];       

  }    

  change(value) {

    this.searchParams = value;
    this.stateChange.next(this.searchParams);        

  }

}

然后在你的组件中......

import {Component} from 'angular2/core';
import {MyService} from './myService';   


@Component({
  selector: 'my-directive',
  pipes: [keyValueFilterPipe],
  templateUrl: "./src/someTemplate.html",
  providers: [MyService]    

})

export class MyDirective {

  public searchParams: string[];

  constructor(private myService: MyService) {
      this.myService = myService;
      myService.stateChange.subscribe(value => { this.searchParams = value; console.log('Change made!') })
  }

change(){

  this.myService.change(this.searchParams);

}

}

您必须订阅eventemitter,然后更新您的变量。服务中的更改事件将被激活... ...

 (click)="change()"