在互联网上,我找到了如何与服务共享数据的示例:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
然后我们订阅更改
subscription: Subscription;
this.subscription = this.dataService.getData()
.subscribe(data => {
this.someData= data;
});
Run Code Online (Sandbox Code Playgroud)
好的,这工作正常.但是,如果我想分享多个元素?为每个元素复制此代码似乎是不合理的,只更改名称.但我找不到任何抽象的解决方案.也许使用带有名称和数据本身的地图,但我无法理解如何在这种情况下订阅更改以及应该如何看待服务.