网站搜索

在 Angular 6/Typescript 中广播事件


我有以下结构:

<app>
  <test-a></test-a>
  <test-b></test-b>
</app>

@Component({
    selector: 'app',
    templateUrl: './app.component.html',
})
export class AppComponent {
}    

@Component({
    selector: 'test-a',
    templateUrl: './testa.component.html',
})
export class TestAComponent {
}

@Component({
    selector: 'test-b',
    templateUrl: './testb.component.html',
})
export class TestBComponent {
}

Test B 包含可选择的项目。当选择其中一个时,我想告诉 Test A 该项目已被选中...

我认为我知道有两个可以实现这一点的选项。

  • 使用 App 来存储选中的项目。在 Test B 中修改该选中的项目,然后让 Test A 做出响应……但这会在 Test A 和 Test B 组件之间……以及父组件 App 之间产生一个 丑陋的紧耦合。我不喜欢这个主意。
  • 创建某种“事件订阅者”服务,用于存储可以被订阅的各种 Observable 数组。我目前的实现(未完成):

// 我的类需要模型

export class KeyValuePair<T>
{
    public key: string;
    public value: T;

    construct(key: string, value: T) {
        this.key = key;
        this.value = value;
    }
}

// 我的实现可能是这样的(进行中)

import { Observable, of } from "rxjs";
import { KeyValuePair } from "../models/keyvaluepair";
import { Injectable } from "@angular/core";

@Injectable({
    providedIn: 'root',
})
export class EventService<T>
{
    protected subscriptions: KeyValuePair<Observable<T>>[];

    public Broadcast(key: string, value: any)
    {
        var observable = new Observable<T>();
        observable.subscribe((a) =>
        {
            return of(value);
        });

        this.subscriptions.push(
            new KeyValuePair<Observable<T>>(
                key, 
                observable
            )
        );
    }

    public Subscribe(key: string): Observable<T>
    {
        var observable = this.subscriptions.find((sub) => {
            return sub.key == key;
        });

        return observable.value;
    }
}

// 你可能如何创建一个事件

this.testEventService.Broadcast("itemSelected", item);

// 它可能如何被使用

this.testEventService.Subscribe("itemSelected").subscribe((item) => {
    this.changeItem(item);
});

然而,我肯定不应该必须写这些东西吧..? 在 AngularJS 和 jQuery 中有一种 $broadcast 和 $on 的东西,让生活变得非常简单... 我这里漏掉了什么吗?在 Angular 6 和 TypeScript 中有更简单的方法吗?

编辑:

我做了一个人们可以使用的服务,请告诉我它是否糟糕:https://jsfiddle.net/jimmyt1988/oy7ud8L3/

答案#1

你可以使用主题

export class EventService<T> {
    protected _eventSubject = new Subject();
    public events = this._eventSubject.asObservable();

    dispathEvent(event) {
       this._eventSubject.next(event);
    }
}