In my HomeComponent
, I am currently using *ngIf
to switch between 3 components. The focus right now is on the relationship between two of them - the ProductListComponent
and the ProductDetailComponent
. Inside the ProductListComponent
, there is a ProductListItemComponent
for iterating through each product. Within my HomeService
, I am utilizing a variable of type BehaviorSubject
that the HomeComponent
subscribes to in order to react to the *ngIf
conditions. Here's how it is set up:
//variable with initial value
private FrameToggle: BehaviorSubject<string> = new BehaviorSubject('product-list');
//variable to watch BehaviorSubject as Observable
CurrentToggle = this.FrameToggle.asObservable();
//function to set the BehaviorSubject
setFrameToggle(page: string){ this.FrameToggle.next(page); }
Both the ProductListItemComponent
and ProductDetailComponent
import the HomeService
as a provider and access the setFrameToggle()
function as follows:
sendPageToggle(page: string){ this.homeService.setFrameToggle(page); }
The button in the templates triggers it like this:
<button (click)="sendPageToggle('value-to-trigger-desired-component'")>some text</button>
Everything works as expected, toggling the components on and off when the buttons are clicked.
However, while trying to fetch data in the ProductDetailComponentService
to provide for the ProductDetailComponent
, I encountered asynchronous issues because the ProductDetailComponent
was loading before the data was fetched.
To resolve this, I imported the ProductDetailComponentService
into the ProductListItemComponent
as a provider. Then, I imported the HomeService
into the ProductDetailComponentService
and used an async
function to fetch the data first and then set the FrameToggle
variable in the HomeService
. The function looks like this:
async prepareData(key: string, page: string){
await (()=> {this.ProductData = this.setData(page);})();
this.homeService.setFrameToggle(key);
}
I created a function in my ProductListComponent
to call this function, which successfully loads the data. However, the component does not toggle as expected when calling the setFrameToggle()
function from within the component.
I added console.log()
statements to check the ProductData
variable inside the prepareData()
function and also to the setFrameToggle()
function in the
HomeService</code, which both showed successful results. Even after simplifying the function by removing <code>async
and testing, the components still did not toggle. The HomeService
is properly imported into the ProductDetailComponent
's module as a provider. I'm unsure what could be causing this issue. Can anyone identify where I might be going wrong?