I want to emit a string when the util.service.ts handled some errors, so that i can get this message in app.component.ts and show it, but i can not subscribe the emitter. this is my code, but it do not work:
in util.service.ts:
export class UtilService {
errMsgEmitter = new EventEmitter();
private handleError(error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body['error'] || JSON.stringify(body);
errMsg = `${error['status']} - ${error['statusText'] || ''} ${err}`;
} else {
errMsg = error['message'] ? error['message'] : error.toString();
}
console.error(errMsg);
this.errMsgEmitter.emit(errMsg);
return Observable.throw(errMsg);
}
/**
* get event emitter
* @returns {EventEmitter<any>}
*/
getNavChangeEmitter() {
return this.errMsgEmitter;
}
in app.component.ts i have this:
ngOnInit() {
this.utilService.getNavChangeEmitter()
.subscribe(data => {
this.errMsg = data;
});
}
Can anybody help me? Thanks a lot
Suddenly I resolved this by make a static Subject:
util.service.ts:
static errSubject: BehaviorSubject<any> = new BehaviorSubject<any>('');
app.component.ts:
UtilService.errSubject
.subscribe(data => {
this.errMsg = data;
});
and do not forget provide UtilService in app.module.ts