【问题标题】:Angular 2 - Passing data from child (within router-outlet) to parent componentAngular 2 - 将数据从子组件(在路由器出口内)传递到父组件
【发布时间】:2017-08-21 04:06:25
【问题描述】:

我有一个包含以下内容的父容器:

<div id="pageContainer">
        <router-outlet></router-outlet>
</div>

<div>
    <div class="title">{{text}}</div>
</div>

我还有一个服务,我打算使用它来将数据从子组件(在路由器插座内)传递到父组件:

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

@Injectable()
export class NotificationsService {


    emitChange(change: any) {

        return change;

    }

}

子组件调用服务方法:

this.notificationsService.emitChange('Data from child');

然后父组件从服务中分配{{text}}:

constructor(
        private notificationsService: NotificationsService
    ) {
        notificationsService.emitChange(
            text => {
                console.log(text);
            });
    }

但这仍然不起作用,有什么想法吗?

【问题讨论】:

  • 父组件中是否有文本属性?
  • 为什么要在路由器插座内传递数据?有具体原因吗?如果您的父组件中使用了您的子组件,您可以只使用 EventEmitter 来传递数据。
  • @KerimEmurla 因为我必须在整个应用程序中多次显示通知框,而且必须从任何地方向它传递一些数据似乎是有意义的。

标签: angular typescript


【解决方案1】:

使用主题来做到这一点

import { Injectable } from '@angular/core';
import { Subject, BehaviorSubject } from "rxjs/Rx";

@Injectable()
export class NotificationsService {
  emitChange$: Subject<any> = new BehaviorSubject<any>(null);
  constructor() { }
  emit(value: any) {
    this.emitChange$.next(value);
  }
  get emitChange(): BehaviorSubject<any> {
    return (this.emitChange$ as BehaviorSubject<any>);
  }
}

在你的孩子身上

this.notificationsService.emit('Data from child');

在父母中

constructor(
    private notificationsService: NotificationsService
) {
    notificationsService.emitChange.subscribe(
        text => {
            console.log(text);
        });
}

顺便说一句,如果您的子组件直接在父组件中使用,您可以使用 EventEmitter 在它们之间进行通信。

【讨论】:

  • 这是初始值,你用这个代码调用函数了吗this.notificationsService.emit('Data from child');
  • 是的,我在 ngOnInit() 的子组件上试过了
猜你喜欢
  • 2016-06-05
  • 1970-01-01
  • 2016-08-28
  • 1970-01-01
  • 1970-01-01
  • 2016-09-05
  • 2017-08-30
  • 2018-12-24
  • 2016-07-06
相关资源
最近更新 更多