将事件传递给指令并订阅它

Pass event to directive and subscribe to it

我有一个输出为 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'))
  }
}

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

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);

根据我之前的回答和您的解释,这次我答对了您的问题。

对于您的解决方案,您可以通过多种方式来执行您想要的操作。

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

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

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

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

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

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