Use parent component's variable, in its method that is invoked by a child component

I'm using a child component:

<app-photo-editor [addPhotoUrlExtension]="'users/add-photo'" [onUploadSuccess]="onUploadPhotoSuccess"
                [deletePhoto]="onDeletePhoto"></app-photo-editor>  

and passing it the onUploadPhotoSuccess function:

 onUploadPhotoSuccess(response: any) {
    if (response) {
      const photo = JSON.parse(response);
      this.member.photoUrl = photo.url;  // offending line
      ...

On the child component, I accept the function, and invoke the parent's function:

export class PhotoEditorComponent implements OnInit {
  @Input() onUploadSuccess: (response: any) => void;

...

this.uploader.onSuccessItem = (item, response, status, headers) => {
      if (response) {
        this.onUploadSuccess(response);
      }
    }  

This gives an error on the offending line (marked above), saying:

core.js:6498 ERROR TypeError: Cannot set properties of undefined (setting 'photoUrl')
    at PhotoEditorComponent.onUploadPhotoSuccess [as onUploadSuccess] (member-edit.component.ts:67:27)
    at FileUploader.uploader.onSuccessItem (photo-editor.component.ts:60:14)
    at FileUploader._onSuccessItem (ng2-file-upload.js:1326:1)
    at XMLHttpRequest.xhr.onload [as __zone_symbol__ON_PROPERTYload] (ng2-file-upload.js:1073:29)
    at XMLHttpRequest.wrapFn (zone.js:763:1)
    at ZoneDelegate.invokeTask (zone.js:406:1)
    at Object.onInvokeTask (core.js:28679:1)
    at ZoneDelegate.invokeTask (zone.js:405:1)
    at Zone.runTask (zone.js:178:1)
    at ZoneTask.invokeTask [as invoke] (zone.js:487:1)  

Which means this.member is undefined, now on one hand it does makes sense I would have needed to pass it to the child component, but on the other, I THINK this worked as is.. So I'm not sure what's the right solution..


This is because you're passing a regular function to another component and therefore the this keyword is not referring to the original component.

You should either use arrow functions for onUploadPhotoSuccess or bind this to it.

onUploadPhotoSuccess = (response: any) => {