有没有办法在模块中使用BehaviourSubject?

时间:2018-01-31 13:58:51

标签: angular angular5 behaviorsubject

我想使用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() {
     }
   }

1 个答案:

答案 0 :(得分:-1)

据我所知,不可能直接进行,但你可以使用&#34;自定义事件hadler&#34;并构建类似于: 服务:

onCurrencyChange(callbackFN: (currency: CurrencyModel) => void): void {
 someEventArray.push(callbackFN);
}

然后如果更改默认货币,请执行以下操作:

someEventArray.forEach(event => event(newDefaultCurrency));