Reputation: 127
I'm currently trying to make a parent component and child component.
When child component is loading data from REST, the parent should display a loading gif. Here is the code:
common.service.ts
import { Injectable } from "@angular/core";
import { Subject } from "rxjs";
@Injectable()
export class CommonService{
private isLoadingSource = new Subject<boolean>();
public isLoading$ = this.isLoadingSource.asObservable();
setLoading(loading: boolean) {
this.isLoadingSource.next(loading);
console.log(loading);
}
}
app.component.ts
import { Component, Inject, OnInit } from "@angular/core";
import { NavService } from "./core/nav";
import { CommonService } from "common.service";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.scss"],
providers: [
NavService,
CommonService
]
})
export class AppComponent implements OnInit {
public loading: boolean = false;
constructor(private commonService: CommonService) {
this.commonService.isLoading$.subscribe(next => {
this.loading = next;
alert(next);});
}
}
child.component.ts
import { Component, OnInit, ViewChild, AfterViewInit, ViewChildren, QueryList } from "@angular/core";
import { CommonService } from "common.service";
@Component({
selector: "child",
templateUrl: "./child.html",
styleUrls: ["./child.scss"],
providers: [
CommonService
]
})
export class child implements OnInit, AfterViewInit {
constructor(
private commonService: CommonService,
) { }
public beforeLoading(): void {
this.commonService.setLoading(true);
}
public afterLoading(): void {
this.commonService.setLoading(false);
}
}
When I run the code the console logged some true and false records, but the listener in app.component.ts
doesn't receive a response.
There is no alert message popping up.
Upvotes: 2
Views: 166
Reputation: 73
The reason this doesn't work is because you provide the service, not as a singleton but as seperate instances per component. It is instantiated twice and thus does not share it's data.
@Injectable({
providedIn: "root"
})
Try adding this to your service and remove the
providers: [CommonService]
from both child and app component.
This provides the service at the root level of your application and is used as a singleton.
I've created a working stackblitz that you can look at:
https://stackblitz.com/edit/angular-ivy-wpdyv9?file=src/app/child.component.ts
Upvotes: 4