簡體   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