繁体   English   中英

Angular2:将数据从一个组件发送到另一个组件并处理该数据

[英]Angular2: Send data from one component to other and act with the data

我正在学习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组件是这两个组件的父组件。 两者都不是彼此的父母

这就是我现在的样子:

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)
  }

}

像这样创建服务...

    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);

}

}

您必须订阅事件发射器,然后更新变量。 该服务中的change事件将被诸如...

 (click)="change()"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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