In my code, I've structured it as follows:
<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
is designed to handle selectable items. The challenge lies in notifying Test A
when an item is selected...
I believe there are two possible solutions for this scenario.
- The first option involves using the
App
component as a middleman to store and pass along the selected item information betweenTest B
andTest A
. However, this approach creates a rather tight coupling between the components that may not be ideal. - The second option proposes creating an "Event Subscriber" service that manages a collection of Observables which can be subscribed to. My initial implementation draft is outlined below:
// This is the model needed for my custom class
export class KeyValuePair<T>
{
public key: string;
public value: T;
construct(key: string, value: T) {
this.key = key;
this.value = value;
}
}
// Preliminary implementation of the concept (work in progress)
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;
}
}
// How to trigger an event
this.testEventService.Broadcast("itemSelected", item);
// Sample usage
this.testEventService.Subscribe("itemSelected").subscribe((item) => {
this.changeItem(item);
});
Despite this solution, I can't help but wonder if there's a simpler way to achieve the desired functionality... In previous frameworks like AngularJS and jQuery, features such as $broadcast and $on simplified event handling. Is there a more straightforward approach in Angular 6 and TypeScript?
Edit:
I've created a service that others can use. Please provide feedback on its effectiveness: https://jsfiddle.net/jimmyt1988/oy7ud8L3/