In the Internet I found such example how to sharing data with a service:
import { Injectable } from '@angular/core';
import {Subject} from 'rxjs/Subject';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class DataService {
private subject = new Subject<any>();
sendData(phone: any) {
this.subject.next(phone);
}
clearData() {
this.subject.next();
}
getData(): Observable<any> {
return this.subject.asObservable();
}
}
Then we subscribe to changes
subscription: Subscription;
this.subscription = this.dataService.getData()
.subscribe(data => {
this.someData= data;
});
Ok, this work fine. But if I want to share more than one element? It seems unreasonable to copy this code for every element, changing only the name. But I can't find any abstract solutions. Maybe using map with the names and the data itself, but I can't understand how to subscribe to changes in this case and how should look like the service.