enable.service.ts
@Injectable({
providedIn: 'root'
})
export class EnableService {
isEnabled$ = from(this.client.init()).pipe(
switchMap(() => this.client.getEnabled()),
map(([enabled, isAdmin]) => ({enabled: true, isAdmin: false})),
share()
); // The observable returns enable and isAdmin values
constructor(
// Some constructor
) {}
}
main.component.ts
export class MainComponent implements OnInit, AfterViewInit, OnDestroy {
@ViewChild('mymap') containerRef: ElementRef<HTMLDivElement>;
isAdmin: boolean = false;
isEnable: boolean = false;
constructor(
private enableService: EnableService,
) {
this.enableService.isEnabled$.subscribe(res => {this.enable = res.enabled; this.isAdmin = res.isAdmin});
}
async ngAfterViewInit(): Promise<void> {
// A hack to wait for the enableService subscription to get the actual value, otherwise containerRef #mymap may not exist
await new Promise(resolve => setTimeout(resolve, 1000));
// Execute third party sdk initialization only if containerRef exists
if (this.containerRef) {
// Third party SDK initialization code here
}
}
main.component.html
<div #mymap *ngIf="!isEnable || isAdmin"></div>
This code currently works with a 1-second delay in ngAfterViewInit. However, what if the enableService takes longer to retrieve the value? It could potentially break the functionality.
Is there a way to ensure that ngAfterViewInit is executed after the enableService retrieves the value?
Or perhaps there is a better approach that avoids using the 1-second delay. Setting the initial value of isEnable to false and then changing it to true could cause issues, similarly setting it to true when it's already true might cause errors. Moving the observable subscription from the constructor to ngOnInit did not solve the issue.