Home > Enterprise >  How to execute angular subject/eventEmitter by start of the website?
How to execute angular subject/eventEmitter by start of the website?

Time:11-07

data.service.ts

testData$ = new Subject<any>();


initData() {
      this.getDataFromApi().subscribe((response) => {
        this.testData$.next(response)
      });
}


getInitData() {
      return this.testData$;
    }

parent.component.ts

ngOnInit(): void {
  this.dataService.initData();
}

child.component.ts

ngOnInit(): void {
  this.dataService.getInitData().subscribe((response) =>
    {
      console.log(response);
    })
}

In this situtation, when I getting first time on the website console.log in child.component.ts is not executed. It is executed after I go to another component (another tab on my website) and then get back to tab in which I have parent and child component. What to do to execute console.log when I getting first time on the website?

I have tried what I wrote.

CodePudding user response:

I recommend doing this instead:

private testData$

initData() {
  this.testData$ = this.getDataFromApi().pipe(
    shareReplay(1)
  );
}

getInitData() {
  return this.testData$;
}

This allows you to not worry about timing, avoid the anti-pattern of multiple layers of subscribing, and not expose Subject.next() outside of your service.

CodePudding user response:

You should return your subject as observable and return same subject data type.

Old

getInitData() {
  return this.testData$;
}

New

getInitData() :Observable<any>{
  return this.testData$.asObservable();
}
  • Related