0

I have main component home.component.ts:

ngOnInit() {
  this.metaService.getMetaCompany()
    .subscribe((response: Json) => {
      let metaCompany = <MetaCompany>response.data;
      this.interactionService.setGlobalMetaCompany(metaCompany);
    });
}

interaction.service.ts:

private globalMetaCompanySource = new Subject<MetaCompany>();
globalMetaCompany$ = this.globalMetaCompanySource.asObservable();
setGlobalMetaCompany(metaCompany: MetaCompany) {
  this.globalMetaCompanySource.next(metaCompany);
}

and component where I need to get data left-menu-admin.component.ts:

constructor(private interactionService: InteractionService) {
  this.globalMetaCompanySubscription = this.interactionService.globalMetaCompany$.subscribe(
    (metaCompany: MetaCompany) => {
      this.companyName = metaCompany.companyName;
      this.avatarUri = metaCompany.avatarUri;
    });
}

So when app starts I got MetaCompany data via ajax query into home.component.ts and when I go to /admin page I don't see method in constructor of left-menu-admin.component.ts is executed. When I press F5 on /admin page -> page reloads and method in constructor is executed. What am I doing wrong? And how can I pass some data to another page?

A. Gladkiy
  • 3,134
  • 5
  • 38
  • 82

1 Answers1

1

In interaction.service.ts, your globalMetaCompanySource is of type Subject<MetaCompany>. But Subject doesn't store value that you assign to it. When you use next() on subject, and then subscribe to it, nothing will happen. If you subscribe first, and then call next() on it, then subscription will evoke its action.

In your case, you can simply use BehaviourSubject instead of Subject. BehaviourSubjects stores the value that you push to it, and when you subscribe to it, it returns last emitted value.

Here you have explanation with examples on BehaviourSubject vs Subject - What is the difference between Subject and BehaviorSubject?

M G
  • 107
  • 10