0

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: 'abc@def.com', 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://edmondtm@bitbucket.org/edmondtm/dialog-error.git

edmondtm
  • 55
  • 1
  • 5

1 Answers1

1

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/

Aamir Khan
  • 2,945
  • 2
  • 25
  • 32
  • Dear Aamir Khan, I got my error sorted and now my codes are running. And also the extra reading material will help me better understand scopes. My gratitude for your help. Thank you so much. I think there is problem with angular documentation. https://angular.io/tutorial/toh-pt6 – edmondtm Oct 31 '17 at 09:06
  • @edmondtm That's because the `handleError` method in your code doesn't return anything although the docs do return a `Promise`. – Edric Oct 31 '17 at 15:30