Using Angular 5 to transfer a callback function to an external script within Angular

Utilizing an external 3rd party script, I am trying to trigger a function called show_end_screen (found below)

Within my component

import { Router } from '@angular/router';
import { init_game, start_game, stop_game } from '../../assets/js/game';

@Component({})

export class PlayComponent implements OnInit {
    constructor(public router:Router) {}
    ngOnInit() {
        init_game(this.show_end_screen) // load ready
    }
    show_end_screen(data){
        console.log(data) //this works
        this.router.navigate(['play']); //"this" is undefined
    }
}

init_game(this.show_end_screen) <== At this point, I am passing show_end_screen to the imported script. When the 3rd party script executes show_end_screen(data), I am able to successfully log the data to the console. However, I do not have access to this or any other Angular reference.

this.router.navigate(['play']); <== This line triggers a console error

ERROR TypeError: Cannot read property 'nav' of undefined

Answer №1

When passing a class-bound method as a value, it loses the context (this). To address this issue, you can either explicitly bind or lexically bind within the callback function:

ngOnInit() {
  // Explicit binding
  init_game(this.show_end_screen.bind(this));

  // Lexical binding
  init_game(data => this.show_end_screen(data));
}

An alternative approach is to use an instance-bound method for your component instead.

show_end_screen = data => {
  this.router.navigate(['play']);
}

Answer №2

The reason behind this issue is that this points to the calling context, not the context where you assign your callback. To resolve this, clarify the context to which this should refer by using the bind function.

To successfully tackle this problem, modify your code as follows:

ngOnInit() {
    init_game(this.show_end_screen.bind(this))
}

Answer №3

It seems like this.router is expected to be initialized in the constructor function

In addition to @Explossion Pills' response, another approach could be defining your method as a property to avoid repetitive bind() calls

show_end_screen = (data) => {
  console.log(data) //this works
  this.router.navigate(['play']); //"this" is undefined
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular2 Dependency Injection with NPM-MQTT

I'm facing some challenges integrating the MQTT package into my Angular2 TypeScript project (created with angular-cli). When using var mqtt = require('mqtt');, I encounter the error Cannot find name 'require'. Therefore, I attemp ...

What are the steps for running an Angular 7 application on both Android and iOS devices?

Currently in the process of developing an application using Angular 7. Any tips on ensuring optimal performance on mobile devices? The app functions smoothly on desktops in aot mode; however, loading time on Android devices is exceedingly slow (approximat ...

Can Typescript classes be hoisted if I use two classes in my code?

Exploring Class Definitions Certain Rules to Comply With Ensuring that the class is defined in advance helps avoid errors. class Polygon { log() { console.log('i am polygon'); } } const p = new Polygon(); // Expected: no errors p.log(); U ...

The mat-select element is defaulting to the last value in a loop for all dropdown selections

I am working with a Mat-select tag that is inside a loop using *ngFor, and by default, it is selecting the last value for all dropdowns. <div *ngFor="let investment of data.priorInvestmentExperiences; > <mat-form-field appearance="outline" ...

Communication between Angular services and the issue of 'circular dependency detected' alerts

I am encountering a circular dependency issue with my AuthenticationService and UserService. The UserService is included within the AuthenticationService, but when I try to use AuthenticationService in UserService as shown below: constructor(private authS ...

Jasmine was unsuccessful in detecting a exported function being invoked by another function

In my code, I've created 2 helper functions where one is a shortcut to the other. I need to verify in my test that the shortcut function is actually calling the main function. Both functions are located in the same file: export function test1(param1, ...

Guide to setting a default value for a select option in Angular 2+

I am having trouble setting a default option in my select box using the html selected property. I want the selected option to be assigned to StartingYear, but currently it's not working as expected. <select [(ngModel)]="StartingYear"> < ...

Tips on obtaining a unique value that does not already exist in a specific property within an Array of objects

I am faced with a challenge involving an array that contains objects with both source and target properties. My goal is to identify a value that never appears as a target. My current approach seems convoluted. I separate the elements of the array into two ...

Angular 7 ERROR: The SystemJS reference is missing

In the process of developing an Angular 7 project with systemjs for dynamic module loading, I encountered an issue. Upon attempting to utilize it, I encountered the following error: ERROR ReferenceError: SystemJS is not defined Within my package.json f ...

How can I eliminate the back button from my personalized login component in ngx-admin/Nebular?

After carefully following the steps outlined in the guide from , I successfully created a custom login component. However, I am now facing an issue - how do I remove the back button from this component? https://i.sstatic.net/WJT64.png ...

The integration of Angular and Node API within the IISNode directory structure is experiencing functionality issues

Read more about the question I have successfully set up my Node API and Angular component with IISnode. However, when accessing the application from the IIS server, I noticed that they are showing in different directories (see image below). Additionally, I ...

What steps can I take to make my animation work in the opposite direction as well?

I'm currently working with an angular slider that is set to TRUE/OPEN by default. The issue I am facing is that while I am able to slide it using angular animations in one direction, I am unable to see the transition when sliding it back. Any assistan ...

Error in TypeScript: The property "component" is not found on the React MUI MenuItem

I am currently working with the react mui MenuItem component and I am trying to turn a menu item into a link. Here is how I have attempted to achieve this: <MenuItem component={<Link href={`/backend/api/exam/${row.id}/result`} />} className={c ...

Unable to modify the height and color of tabs in Angular 6

I am in the process of learning Angular, CSS, and HTML. I have been using MatTabsModule to create tabs, but I am having trouble adjusting the height, background, and other properties of the tabs. I am struggling to override the default properties of MatTab ...

Is there a way to use a single url in Angular for all routing purposes

My app's main page is accessed through this url: http://localhost:4200/ Every time the user clicks on a next button, a new screen is loaded with a different url pattern, examples of which are shown below: http://localhost:4200/screen/static/text/1/0 ...

Tips on storing and retrieving data between pages in Ionic 4/5: Saving data to a service and accessing it from a

Looking for assistance from the community I am trying to pass data between pages using a service in Angular. Here is the code for the parent component.ts file: import { Component } from '@angular/core'; import { ShareService } from '../sh ...

ERROR: The variable countryCallingCode has not been defined

I encountered an error when attempting to assign a value to my property countryCallingCode, which does not exist in the first option. this.allData.customerFacingPhone.countryCallingCode = newItem.countryCallingCode The error message I received was: ERROR ...

Error encountered when building with --prod flag due to AngularFireFunctions injection issue

After successfully using AngularFireFunctions in a modal during development, I encountered an error after compiling with the --prod flag. The issue seems to be related to the '"optimization": true' setting in the angular.json file and its intera ...

Expo + tRPC: Oops! Looks like the application context couldn't be retrieved. Don't forget to wrap your App inside the `withTRPC` HoC for

I'm currently working on a straightforward tRPC server setup: // server.ts import { initTRPC } from "@trpc/server"; import { z } from "zod"; const t = initTRPC.create(); export const appRouter = t.router({ greeting: t.procedu ...

Is it possible to lengthen a function in TypeScript?

I am part of a team responsible for maintaining a unique JavaScript library that generates spy functions. These spy functions are designed to allow users to monitor how a function is called, primarily used in the context of unit testing. Our library creat ...