我希望在更新子组件时更新父组件 . 我试图使用事件 Launcher 实现这一点,但我使用路由器插座来调用子组件 . 我不知道该怎么做 .
任何人都可以指导我该怎么做才能得到这个?
谢谢
您无法直接从子组件更新父组件 . 但您可以创建一个可以从任何组件交互到任何其他组件的服务,如下所示 .
创建一个文件 communication.service.ts
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 => { // ... }) } }
1 回答
您无法直接从子组件更新父组件 . 但您可以创建一个可以从任何组件交互到任何其他组件的服务,如下所示 .
创建一个文件
communication.service.ts
在儿童组件中
在父组件中