Я столкнулся с проектом в процессе, пусть несколько несвязанных компонентов уведомляют друг друга о данных обновления, есть ли более чистый метод кодирования?
Есть 3 компонента (более вероятно позже) и общие данныесоставная часть.Они не имеют отношения родитель-потомок друг с другом и отображаются только на одном экране.
Желаемый эффект заключается в нажатии кнопки любого компонента, обновлении содержимого общих данных и уведомлении себя и других компонентов.для получения новых сообщений из общих данных.
В настоящее время мой подход заключается в использовании Observable и Subscription для Rx, но они должны быть импортированы в файлы component.ts и service.ts каждого компонента, а такжепоявляется дубликат кода, он очень грязный, я не знаю, что лучше.практика?
Спасибо!
Мой код: Имя примера test-a-comp (abc и т. д., код тот же)
test-a-comp.html
<p>
{{ownMessage}}
</p>
<button (click)="sendChange()">update</button>
test-a-comp.component
import { Component, OnInit } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { CommonData } from '../common-data/common-data';
import { TestACompService } from './test-a-comp.service';
import { TestBCompService } from '../test-b-comp/test-b-comp.service';
import { TestCCompService } from '../test-c-comp/test-c-comp.service';
@Component({
selector: 'app-test-a-comp',
templateUrl: './test-a-comp.component.html',
styleUrls: ['./test-a-comp.component.css']
})
export class TestACompComponent implements OnInit {
subscription: Subscription;
ownMessage;
constructor(
private testAService: TestACompService,
private testBService: TestBCompService,
private testCService: TestCCompService,
) {
this.subscription = this.testAService.getMessage()
.subscribe((test) => {
CommonData.message = test;
});
this.subscription = this.testBService.getMessage()
.subscribe(() => {
this.ownMessage = CommonData.message;
});
this.subscription = this.testCService.getMessage()
.subscribe(() => {
this.ownMessage = CommonData.message;
});
}
ngOnInit() {
}
sendChange() {
this.testAService.sendMessage();
}
}
test-a-comp.service:
import { Injectable } from '@angular/core';
import {Subject} from 'rxjs/Subject';
import {Observable} from 'rxjs/Observable';
import {Subscription} from 'rxjs/Subscription';
@Injectable()
export class TestACompService {
subscription: Subscription;
private subject = new Subject<any>();
constructor() {
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
sendMessage(): void {
this.subject.next('update message from A');
}
}