export class Component implements OnInit {
error$: Observable<string>;
constructor(
private errorService: ErrorHandlerService
) {
this.errorService.errorPublic.subscribe((errorres) => {
console.log('Component subscribed to error: ' + errorres);
if (errorres) {
this.error$ = of(errorres);
}
});}
@Injectable({
providedIn: 'root',
})
export class ErrorHandlerService {
private errorSubject = new BehaviorSubject<string | null>(null);
public errorPublic: Observable<string | null> =
this.errorSubject.asObservable();
handleError(error: any) {
let errorMessage = 'An unknown error occurred';
this.errorSubject.next(errorMessage);
console.log(errorMessage);
console.error(errorMessage);
return throwError(errorMessage);
}
}
- Component subscribed to error: null Component.component.ts:35
- POST localhost:8080/auth/login 401 (Unauthorized)
- HTTP Error: Wrong password errorHandler.service.ts:37
- HTTP Error: Wrong password errorHandler.service.ts:39
I am trying to implement error handling in my Angular component. After the component is opened, the constructor handles its initialization, and I receive my first point with the variable 'null' correctly set.
Next, I send a bad request and receive point 2. Then, I attempt to update my errorSubject via errorPublic and send it to my error$ in the component. At this point, I encounter a problem because, as we can see, I receive both console logs from ErrorService, but my component doesn't display something like this:
- Component subscribed to error: An unknown error occurred Component.component.ts:35
My component isn't receiving the updated value from errorSubject, and I'm unable to display this information on the layout.
Edit:
private errorSubject = new ReplaySubject<string>(1);
public errorPublic: Observable<string> = this.errorSubject.asObservable();
public testError: string;
constructor() {
this.errorPublic.subscribe((error) => {
this.testError = error;
console.log('error from service info: ' + this.testError);
});
}
error from service info: HTTP Error: Wrong errorHandler.service.ts:23
When I place this subscription in the constructor of my service, it logs information about changes to the console, but my component didn't:
constructor() {
this.errorService.errorPublic.subscribe((error) => {
this.error = error;
console.log('error from component: ' + this.error);
});
}