【问题标题】:Using input/output events to trigger methods in a parent component in Angular 2在 Angular 2 中使用输入/输出事件触发父组件中的方法
【发布时间】:2016-03-04 10:29:42
【问题描述】:

子服务如何将更改通知父组件?我曾经在 Angular 1 中通过 $watching 子服务中的变量来执行此操作。不幸的是,这已经不可能了。

我尝试将服务注入回组件,但失败了,可能是由于循环依赖。根据我在当前文档中可以找到的内容,我想出了以下代码:

AppComponent
 |
SomeComponent
 |
SomeService

应用组件

@Component({
    selector: '[app-component]',
    templateUrl: 'partials/app.html',
    directives: [
        SomeComponent
    ],
    providers: [
        SomeService
    ]
})
export class AppComponent {
    constructor() { }
}

bootstrap(AppComponent);

一些组件

import {Component, Input} from 'angular2/core'
import {SomeService} from '../services/some.service'

@Component({
    selector: 'foo',
    templateUrl: 'partials/foo.html'
})
export class SomeComponent {
    constructor() {}
    @Input set someEvent(value) {
        console.log(value);
    }
}

SomeService

import {EventEmitter, Output} from 'angular2/core'

export class CoreService {
    constructor() {
        this.someEvent = new EventEmitter();
    }
    @Output() someEvent: EventEmitter<any>;
    public foo() {
        this.someEvent.emit(true); // Or next(true)?
    }
}

【问题讨论】:

    标签: javascript angularjs events angular


    【解决方案1】:

    @Output 只能用于组件,不能用于服务。在此级别,您可以使用 (...) 语法注册此事件。

    来自 angular.io 文档 (https://angular.io/docs/ts/latest/api/core/Output-var.html):

    声明一个事件绑定的输出属性。

    当输出属性发出事件时,附加到该事件的事件处理程序会调用模板。

    对于需要明确订阅此事件的服务,如下所述:

    import {Component, Input} from 'angular2/core'
    import {SomeService} from '../services/some.service'
    
    @Component({
      selector: 'foo',
      templateUrl: 'partials/foo.html'
    })
    export class SomeComponent {
      constructor(service:CoreService) {
        service.someEvent.subscribe((val) => {
          console.log(value);
        });
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-27
      • 2018-03-11
      • 2018-10-27
      • 1970-01-01
      • 2020-12-06
      • 1970-01-01
      相关资源
      最近更新 更多