我想使用BehaviourSubject
在两个不同模块的两个组件之间共享数据。我该如何做到这一点?
CurrenciesModule
export class CurrenciesComponent implements OnInit {
defaultCurrency: CurrencyModel;
constructor(private coreServ:CoreService) {
}
ngOnInit() {
this.coreServ.DefaultCurrency.subscribe((val) => {
this.defaultCurrency = val;
console.log({ currNewDefault: this.defaultCurrency });
});
}
selectCurrency(currency: CurrencyModel) {
this.coreServ.changeDefaultCurrency(currency);
}
}
SharedModule
export class ChooseCurrencyComponent implements OnInit {
defaultCurrency: CurrencyModel;
Currencies: CurrencyModel[];
constructor(private coreServ:CoreService) { }
ngOnInit() {
this.coreServ.DefaultCurrency.subscribe((val) => {
this.defaultCurrency = val;
console.log({ chooseNewDefault: this.defaultCurrency });
});
//this.readMany();
}
selectCurrency(currency:CurrencyModel) {
this.coreServ.changeDefaultCurrency(currency);
}
和 CoreService
@Injectable()
export class CoreService {
private defaultCurrency = new BehaviorSubject<CurrencyModel>(null);
DefaultCurrency = this.defaultCurrency.asObservable();
changeDefaultCurrency(currency: CurrencyModel) {
this.defaultCurrency.next(currency);
}
}
最后是模型
export class CurrencyModel {
public ID: string;
public Name: string;
public Rates: [{key:string}];
private form: FormGroup;
constructor() {
}
}
答案 0 :(得分:-1)
据我所知,不可能直接进行,但你可以使用&#34;自定义事件hadler&#34;并构建类似于: 服务:
onCurrencyChange(callbackFN: (currency: CurrencyModel) => void): void {
someEventArray.push(callbackFN);
}
然后如果更改默认货币,请执行以下操作:
someEventArray.forEach(event => event(newDefaultCurrency));