如何在 Angular 2 中从子组件更新父组件

How to update parent component from child component in Angular 2

我想在更新子组件时更新父组件。我试图使用事件发射器来实现这一点,但我正在使用路由器出口来调用子组件。我不知道该怎么做。

任何人都可以指导我我应该怎么做才能得到这个?

谢谢

您不能直接从子组件更新父组件。但是您可以创建一个服务,该服务可以从任何组件与任何其他组件进行交互,如下所示。

创建文件communication.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class CommunicationService {
    constructor() { }

    private emitChangeSource = new Subject<any>();

    changeEmitted$ = this.emitChangeSource.asObservable();

    emitChange(data: {}) {
        this.emitChangeSource.next(data);
    }

}

在子组件中

import { Component } from '@angular/core';
import { CommunicationService } from './communication.service';

@Component({
    templateUrl: `./child.component.html`,
    styles: ['child.component.css']
})
export class ChildComponent{
    constructor(private _communicationService: CommunicationService) { }

    onSomething() {
        this._communicationService.emitChange({proprty: 'value'});
    }
}

在父组件中

import { Component } from '@angular/core';
import { CommunicationService } from './communication.service';

@Component({
    templateUrl: `./parent.component.html`,
    styles: ['./parent.component.css']
})

export class ParentComponent {    
    constructor( private _communicationService: CommunicationService ) { 
        _communicationService.changeEmitted$.subscribe(data => {
        // ...
        })
    }
}