Angular @Output:我们能否在发射时检测功能是否完成?

时间:2017-12-21 11:06:21

标签: angular output observable angular-components eventemitter

我有Angular Component Output。当我emit event到此output时,将调用async函数(此函数位于组件之外)。

component内,我想知道这个外部功能何时完成。有没有办法做到这一点?

这是我的组件的一些代码:

@Output() action: EventEmitter<string>;

itemClicked(item) {
    this.action.emit();
    // When the function of the observer is done: this.hideMenu();
}

以下是组件之外的代码:

<my-component (action)="getData()"></my-component>


getData() : Promise<any> {
    ...
}

有没有办法检测到&#34; getData&#34;函数在组件内完成了吗?

在AngularJS中,我可以这样做:

scope: {
    action: '&'
}
...

    scope.itemClicked = function(item) {
        $q.when(item.action()).finally(function() {
            scope.hideMenu();
        });
    };

修改

我在思考另一个受Ionic复习启发的解决方案。如果emit()调用将组件的实例作为参数传递,该怎么办?这样getData函数可以执行以下操作:

getData(menu): Promise<any> { 
    ...
    menu.hideMenu();
}

您对此解决方案有何看法?如果您认为错了,我想我会选择Input

3 个答案:

答案 0 :(得分:5)

我认为你应该在功能完成时使用set发送已完成的消息,并在感兴趣的组件中使用 <input type="date" min="2017-01-01" max="2017-12-30"> 监听输入并执行您想要的功能完成。

答案 1 :(得分:2)

AngularJS &绑定被错误地翻译为Angular。正确的对应方是Input

@Input() actionCallback: () => Promise<any>;

itemClicked(item) {
    this.actionCallback().then(...);
}

使用方法如下:

<my-component [actionCallback]="getData">

虽然Output提供了不应该反馈的单向交互。 getData应该了解其职责并通过回调或RxJS主题提供反馈:

@Output() action: EventEmitter<Function>;

itemClicked(item) {
    this.action.emit(this.onClick);
}

onClick = () => {
  this.hideMenu();
}

使用方法如下:

<my-component (action)="getData($event)"></my-component>

getData(callback) : Promise<any> {
    ...
    .then(callback);
}

答案 2 :(得分:0)

您可以使用Host属性来获取父级,如此

@Output() action: EventEmitter<string>;

constructor(@Host() private parent: ParentComponent) {
    parent.getData().subscribe(...);
}

编辑键入您的父级作为抽象类

constructor(@Host() private parent: ConcernedParent) {
    parent.getData().subscribe(...);
}

export abstract class ConcernedParent {
  public abstract getData(): Observable<any>;
}