Transitioning from an Angular 1.x website to Angular 2.6

After revamping an old Angular 1.x website, I've hit a roadblock when converting a section of the code.

Original Code:

var loaded = vm.cartMap.on('load', function() {
    loaded.remove();
    setupExtentLayer();
});

function setupExtentLayer() {
    esriLoader.require(['esri/layers/GraphicsLayer'], function (GraphicsLayer) {
        vm.extentLayer = new GraphicsLayer();
        vm.cartMap.addLayer(vm.extentLayer);
        if (vm.cartItems.length > 0) {
            _updateCartStatus();
        }
    });
}

New Code:

const loaded = this.cartMap.on('load', function() {
    loaded.remove();
    this.setupExtentLayer();
});

setupExtentLayer() {
  loadModules(['esri/layers/GraphicsLayer']).then(([GraphicLayer]) => {
    this.extentLayer = new GraphicLayer();
    this.cartMap.addLayer(this.extentLayer);
    if (this.cartItems.length > 0) {
        this._updateCartStatus();
    }
  });
}

I encountered an issue where the angular 2.6 code does not recognize the method setupExtentLayer().

What could be causing this discrepancy?

Answer №1

To ensure the correct binding of the setupExtentLayer function, it may be necessary to bind it within the constructor of the parent class.

One way to achieve this is by adding the following code:

this.setupExtentLayer = this.setupExtentLayer.bind(this);

Answer №2

The issue lies within JavaScript involving the usage of this, not in Angular 2.

this.cartMap.on('load', function() {
    loaded.remove();
    this.setupExtentLayer(); // this refers to JavaScript context here
}.bind(this)); // binding this to the function

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

Using NestJS to inject a Factory provider into another Factory

I've gone through various questions here, but none of them addressed my issue: NestJS - Inject factory provider into another provider doesn't work I'm trying to set up an async provider that retrieves configurations from a remote repositor ...

Using Froala events in Angular 2: A guide

Currently, I am incorporating Froala into my Angular 2 project. I have managed to upload an image successfully but am encountering issues triggering the image.uploaded event. The Froala document provides an example of how the event should be implemented: ...

Transferring Data from Angular Application to Spring Server via Rest Implementation

I am currently facing an issue while attempting to upload a file using Angular and send it to my Spring-based REST backend. I followed the guidance provided in this resource for my Angular service implementation. However, two problems have arisen: The fir ...

Unlocking the essence of objects: extracting their types

Here's a map I have: const Map = { key1: 'value1', key2: 'value2' } I'm looking to create a type value1 | value2 using the object above. Is there a way to do this without repeating the values? I attempted type MyType = ...

Changing the default route in Angular 2 based on conditions

I'm currently developing an application where, upon entering the page, the default route for the user is the "Login" page. However, I want to implement a condition based on whether the user has a local storage variable (id) set. If this variable exist ...

A guide to adding images to dropdown options in Angular 6

I'm having trouble getting an icon or image to appear next to text in a dropdown menu. I'm currently working with Angular 6 and despite trying multiple solutions, I haven't been able to make it work. All I want is to display a flag next to ...

Showing hierarchical JSON data in Angular界面

I'm struggling to figure out how to properly loop through a nested JSON file that I have. Here is the code snippet I have so far: JSON: [ { "product": "vacuum cleaner", "productinformation": [ { ...

Assigning a value and specifying the selected attribute for an options tag

Trying to understand the challenge of setting both a value and a selected attribute on an options tag. Each one works independently, but not together. For example: <select> <option *ngFor="let item of items" selected [ngValue]="item"> ...

Using a module without a declaration file: tips for troubleshooting

I am working on a Node.js project using Typescript and would like to incorporate the npm package country-code-lookup. However, this package does not have type declarations available. Despite the lack of typings, I still want to use this package in my proj ...

The clash between Ngx-Bootstrap Popover and Ngx-popover names causes confusion and hinders compatibility

I have encountered an issue while working on a project that involves ngx-popover. This library is great, but it seems to be limited for a specific case that I am dealing with. My aim is to continue using both libraries, but I am facing conflicts because t ...

What is the best way to incorporate Ekko Lightbox into an Angular 7 Project?

I'm facing an issue while implementing Ekko lightbox in my angular project. Specifically, I want to use it in a certain component but I am unsure about how to import the necessary files into that component. After installing Ekko via NPM, I found all ...

Trigger a dispatched action within an NGRX selector

I want to ensure that the data in the store is both loaded and matches the router parameters. Since the router serves as the "source of truth," I plan on sending an action to fetch the data if it hasn't been loaded yet. Is it acceptable to perform the ...

I am experiencing difficulty showing information in Angular due to an [object Object] error

I encountered the following issue: Error message: Error trying to diff '[object Object]'. Only arrays and iterables are allowed I have a JSON response that I want to utilize to display information like name, coordinates, temperature, minimum t ...

Angular 4 fetches the number obtained from a GET request

In my spring-boot back-end app, I have defined a query as shown below: @Query("SELECT COUNT(*) " + "FROM Foo " + "WHERE name = :name and surname = :surname ") Integer countByNameAndSurname(@Param("name") String name, @Param("surnam ...

AngularJS 2: Modifications to templates or components do not automatically reflect in the user interface

My background is in Angular 1, where everything worked seamlessly. However, I am encountering serious issues trying to create a basic application using Angular 2 in Visual Studio. After carefully following the "5 minute tutorial" and getting it to work, I ...

What could be causing the Typescript error when utilizing useContext in combination with React?

I am currently working on creating a Context using useContext with TypeScript. I have encapsulated a function in a separate file named MovieDetailProvider.tsx and included it as a wrapper in my App.tsx file. import { Context, MovieObject } from '../in ...

Changing Image to Different File Type Using Angular

In my Angular Typescript project, I am currently working on modifying a method that uploads an image using the input element of type file. However, I no longer have an input element and instead have the image file stored in the assets folder of the project ...

Typescript's generic function is unable to recognize the return type defined

How do I implement the listToList function below to meet the following criteria: The listItem and return type must be limited to only string or undefined, no other types allowed If listItem is undefined, then the function should return undefined If listIt ...

Having issues with narrowing down a TypeScript class

Check out this simplified code snippet: class Thing<InState extends boolean = boolean> { public inState(): this is Thing<true> { return true; } } const y = new Thing(); if (y.inState()) { y } When I hover over y in ...

The unexpected identifier 'express' was encountered in the import call, which requires either one or two arguments

I'm in the process of constructing an express server using typescript and Bun. Recently, I completed my register route: import express from "express"; const router = express.Router(); router.get('/registerUser',(_req:express.Reque ...