代码之家  ›  专栏  ›  技术社区  ›  Jimmyt1988

角6/字体的广播事件

  •  0
  • Jimmyt1988  · 技术社区  · 6 年前

    我有以下结构:

    <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 包含可选项。当选择一个,我想告诉测试A,项目被选中…

    我认为有2种选择我能意识到这一点。

    • 使用 App 以存储所选项目。在中修改选定项 测试B 然后允许 Test A 作出反应…但它使 难看的紧耦合 之间 测试A 测试B 组件。。。和父母 应用程序 组件。我不喜欢这个主意。
    • 创建某种“事件订阅服务器”服务,存储可以订阅的各种可观察的数组。我在这里的当前实现(未完成):

    //我自己的类所需的模型

    export class KeyValuePair<T>
    {
        public key: string;
        public value: T;
    
        construct(key: string, value: T) {
            this.key = key;
            this.value = value;
        }
    }
    

    //我的实现看起来如何(WIP)

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

    但是,我当然不应该写这些东西…?在盎格鲁JS和JQuery有一个$$广播和一种让生活如此简单的东西…我错过了什么?有没有一种更简单的方法在角6和打字?

    编辑:

    我已经做了一项服务,人们可以使用,请告诉我,如果它吮吸: https://jsfiddle.net/jimmyt1988/oy7ud8L3/

    1 回复  |  直到 6 年前
        1
  •  3
  •   izmaylovdev    6 年前

    你可以使用 Subject

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