Having a problem with injecting a service into another service. I have a ContactService that retrieves data from the server using the handleError method, and an AlertService that handles errors thrown from the handleError method. Both services are declared in my Core Module. However, when I call alertService.submitNewMessage, it shows that this.alertService is undefined. Any assistance would be appreciated.
@Injectable()
export class AlertService {
private $currentMessages: BehaviorSubject<string> = new BehaviorSubject('');
public currentMessages: Observable<string> = this.$currentMessages.asObservable();
constructor() { }
submitNewMessage(msg: string): void {
this.$currentMessages.next(msg);
}
}
Contact Service:
@Injectable()
export class ContactService {
private contactsUrl = 'http://localhost/customers';
constructor(
private http: Http,
private router: Router,
private alertService: AlertService
) { }
getContactsFromService(): Observable<SubmitCustomerHttp[]> {
return this.http.get(this.contactsUrl)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
return HttpHelper.extractData(res);
}
handleError(error: Response | any) {
let errMsg: string;
console.log('Receive error: ', error);
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
if (error.status === 500 || 400 || 404) {
window.alert(errMsg);
this.alertService.submitNewMessage(errMsg);
return errMsg;
}
} else {
errMsg = error.message ? error.message : error.toString();
console.log('Error Message: ', errMsg);
return null;
}
}
}
Core Module:
@NgModule({
imports: [
CommonModule,
HttpModule,
JsonpModule
],
declarations: [],
providers: [
AlertService,
ContactService,
]
})
export class CoreModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: CoreModule,
providers: [
AlertService,
ContactService,
]
};
}
}