Reputation: 105
I have got trouble when inject service in another Service. I got a ContactService to get data from the server with the handleError method. I got an AlertService to throw error from handleError Method. I have already declared both contactService and AlertService in my Core Module. But when I called alertService.submitNewMessage it shown that this.alertService is undefined. Please help
@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);
}
}
And 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;
}
}
}
My Core Module
@NgModule({
imports: [
CommonModule,
HttpModule,
JsonpModule
],
declarations: [],
providers: [
AlertService,
ContactService,
]
})
export class CoreModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: CoreModule,
providers: [
AlertService,
ContactService,
]
};
}
}
Upvotes: 0
Views: 90
Reputation: 5413
The problem I suspect is related to
return this.http.get(this.contactsUrl)
.map(this.extractData)
.catch(this.handleError);
This registers the class methods as callbacks, which is incorrect because this
will not bind correctly.
You can fix this by wrapping these in arrow-functions, so that this
will still refer to the service and not to the callback function when the code inside is reached:
return this.http.get(data => this.contactsUrl(data))
.map(data => this.extractData(data))
.catch(data => this.handleError(data));
Upvotes: 1