Reputation: 55
Appreciation for taking time to read my post.
I hope more experienced Angular Developers can help me with this error. I have no problem calling dialog in component in component with subscribe and return error in dialog. But as soon as I move it into service, and change it into promise I am getting the following error.
I am thinking it has to do with converting an observable to promise
Uncaught (in promise): TypeError: Cannot read property 'dialog' of undefined TypeError: Cannot read property 'dialog' of undefined
Following are my code in my service:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { MatDialog } from '@angular/material';
import { NotificationDialogComponent } from
'./dialog/notification/notification.dialog';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class TestService {
constructor(
private http: Http,
private dialog: MatDialog
) { }
public PostFakeInfo() {
const url = 'http://www.mocky.io/v2/59f73b612f00002510558579';
const mockRequest = {email: '[email protected]', password: 'abcdef'};
return this.http.post(url, mockRequest)
.toPromise()
.then(response => response.json())
.catch(this.handleError);
}
private handleError(error: any) {
console.error(error);
const dialogRef = this.dialog.open(NotificationDialogComponent, {
data: {
title: 'Error',
message: 'Error Message'
}
});
}
Extra info: Angular Material version 2.0.0-beta.12 Repo available if you want the complete code. https://[email protected]/edmondtm/dialog-error.git
Upvotes: 0
Views: 474
Reputation: 3031
You don't have the this
context of your class in the handleError function because you are passing it directly. Instead, use an arrow (or Lambda) function which will preserve your scope.
.catch(error => this.handleError(error))
Refer also to this answer: https://stackoverflow.com/a/37990958/2227788
A good read on JavaScript scope: https://toddmotto.com/everything-you-wanted-to-know-about-javascript-scope/
A good read on Arrow functions: https://toddmotto.com/es6-arrow-functions-syntaxes-and-lexical-scoping/
Upvotes: 1