#Handle ngOnInit error in parent of lazy-loaded module
3 messages · Page 1 of 1 (latest)
Why wouldn't that be the responsibility of the Component that has the error?
But you can make a Service that you tell when an Error happens, and a component that listens for Errors from the Service.
@Injectable({ providedIn: 'root' })
export class ErrorAlertService {
public readonly error$: Observable<string>;
private readonly _errorSub$: Subject<string>;
constructor() {
this._errorSub$ = new Subject<string>();
this.error$ = this._errorSub$.asObservable();
}
public clearError(): void {
this._errorSub$.next('');
}
public setError(msg: string): void {
this._errorSub$.next(msg);
}
}
@Component({
template: `
<div *ngIf="error$ | async as errorMsg" class="alert alert-danger">
<button (click)="close()" class="btn-close icon-font" type="button">
close
</button>
{{ errorMsg }}
</div>
`,
})
export class ErrorAlertComponent {
public readonly error$: Observable<string>;
constructor(private readonly service: ErrorAlertService) {
this.error$ = this.service.error$;
}
public close(): void {
this.service.clearError();
}
}
The reason I want to make a more general component handle the error is because it's lazy loading one of around 100 different components, and I want to handle failures for when the oninit lifecycle hook fails for whichever component ends up getting loaded. I have spent far too much time trying to code that into a fraction of the components, since they all need to communicate back to the parent that lazy-loads them.