首页 > 解决方案 > 将事件传递给指令并订阅它

问题描述

我有一个具有 EventEmitter 输出的指令。我想在对已发出的事件返回订阅的订阅完成后做一些事情。

(例如,我想在 example.component 的 save() 完成时执行 console.log('test')。 - 我知道我可以在 example.component 的保存方法中做到这一点,但我正在做一些通用的事情所以我在指令中需要它)。

import { Directive, OnInit, HostListener, Output, EventEmitter } from '@angular/core';

@Directive({
  selector: '[appSingleActiveButton]'
})
export class SingleActiveButtonDirective {
  @Output() appSingleActiveButton: EventEmitter<any> = new EventEmitter();

  constructor() {}

  @HostListener('click', ['$event'])
  private onClick(e: any): void {
    this.appSingleActiveButton.next(e);
    //determine somehow that the referred function's subscription is completed and do something
    // for example what I tried is: this.appSingleActiveButton.subscribe(() => console.log('do some other stuff'))
  }
}

我有一个组件,它有一个带有该指令的元素并传递一个返回订阅的函数。

example.component.ts:

import { Component } from '@angular/core';
import { Subscription } from 'rxjs/Rx';
import { Http } from '@angular/http';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.scss'],
})
export class ExampleComponent {

  constructor(private http: Http) {}

  public save(index: number): Subscription {
    const requestUrl = 'http://example.com';
    return this.http
    .get(requestUrl)
    .map((response) => response.json()).subscribe(() => console.log(`doing some stuff ${index}`));
  }
}

example.component.html

<div *ngFor="let btn of btns; let i = index">
    <div (appSingleActiveButton)="save(i)">test directive</div>
</div>

编辑:问题如下:

如何确定save()在我实际调用它的指令中完成(成功或错误)this.appSingleActiveButton.next(e);

标签: angularangular5observableangular2-directiveseventemitter

解决方案


按照我之前的回答和你的解释,这次我解决了你的问题。

对于您的解决方案,您有几种方法可以做您想做的事。

  1. 鉴于指令只做同样的事情(HTTP 调用)

为此,您可以简单地将 URL 作为参数传递给指令,并让指令处理 HTTP 调用。您可以使用 an@Output来检索订阅并在您的组件中订阅它。

  1. 鉴于他们做的事情略有相似,并希望将逻辑保留在您的组件中

您可以将您的函数save直接作为指令传递@Input给您的指令。单击时,您可以运行此函数,然后再次使用 an@Output获取订阅。

您也可以直接在构造函数中引用您的元素,并在单击时调用该元素的函数。

这些是您可以实施的解决方案。如果您在代码方面需要帮助,请随时提出要求,但我不会那样给您,因为我不是您的代码猴子,而尝试是最好的学习方式。


推荐阅读