0

I have the following code

ngOnInit(): void {
  this.getQueryParams(this.generateSafeUrl);
}

getQueryParams(callback) {
  this.route.queryParams.subscribe(params => {
    let analysisId = params['analysisId'] || null;
    callback({ analysisId, domain });
  });
}

generateSafeUrl({ analysisId = null, domain = null }) {
  let url = 'https://my-site.s3-eu-west-1.amazonaws.com/index.html';
  if (analysisId && domain) {
    url = `${url}?analysisId=${analysisId}&domain=${domain}`;
  }
  this.safeSrc = this.sanitizer.bypassSecurityTrustResourceUrl(url);
}

I miss the whole thing that if I don't use a callback and do the following, if it works and the error doesn't occur:

getQueryParams(callback) {
  this.route.queryParams.subscribe(params => {
    let analysisId = params['analysisId'] || null;
    let domain  = params['domain'] || null;
    this.generateSafeUrl({ analysisId, domain });
  });
}

I can't understand why the callback produces the error.

skink
  • 5,133
  • 6
  • 37
  • 58
juanjinario
  • 596
  • 1
  • 9
  • 24

1 Answers1

1

When you're passing a function like this:

this.getQueryParams(this.generateSafeUrl);

its this parameter is set to the caller, i.e. this will be something else inside this.generateSafeUrl.

One correct way of writing this would be:

this.getQueryParams(param => this.generateSafeUrl(param));

Arrow functions capture this and behave more like what you'd expect them to behave.

Alternatively, one could explicitly bind this on the function:

this.getQueryParams(this.generateSafeUrl.bind(this));

There are quite a few answers here that explain function scoping, e.g. https://stackoverflow.com/a/20279485

skink
  • 5,133
  • 6
  • 37
  • 58