It is undefined because we run setLoader inside ngOnInit where view is not ready. At that time, loading$ in service class is still undefined. When template renders it, definitely it is undefined.
I'd move the setLoader to ngAfterViewInit
import { Component, VERSION, AfterViewInit } from '@angular/core'; // import AfterViewInit
import { MyService } from './my.service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit { // add AfterViewInit
constructor(public myservice: MyService) {
}
ngOnInit() {
}
ngAfterViewInit() {
this.myservice.setLoader(true); // move it here
}
}
Also I checked that there's a typo in the template, the original code uses myservice.loader$ but it is supposed to be myservice.loading$.
<div *ngIf="myservice.loading$ | async">
Loading
</div>
Hope it helps