Getting a "function is not defined" error in Angular 6 while using it within a nested function

I'm facing an issue related to typescript, where the following code is causing trouble:

private loadTeams = function(){
    let token =  sessionStorage.getItem('token');
    if(token !== undefined && token !== null && token !== ''){
      this._userService.getUserByToken(token)      
        .subscribe(user => {
          this._teamService.getTeamsByUser(token, user)
            .subscribe(data => {
              this.teamList = data.data;
            }, error => {

            });
        }, error => {

        });
    } else {
      sessionStorage.removeItem('token');
    }
  }

This code snippet throws the following error:

ERROR TypeError: "_this._teamService.getTeamsByUser is not a function"

In various discussions, I have come across suggestions to use arrow functions, but isn't it already using one?

I attempted to set let that = this; and then substitute that for this in the second function, but sadly, it didn't resolve the issue.

Another workaround mentioned by people is to utilize .bind(this), yet I am unsure about where to implement this.

Could someone provide an explanation as to why this error is occurring and offer insight on how to fix it?

Answer №1

Issue resolved! Following your advice, I utilized private loadTeams(){...}. Strangely, I had to restart Angular and run ng serve again for it to take effect.

Answer №2

If you're encountering an issue with your _teamService injection or construction, try declaring the loadTeams function in different ways, as long as the service call is not undefined.

For example,

loadTeams() { ... or loadTeams = function() {... or loadTeams = () => { ...

All three methods should work if everything is properly initialized.

I created a Typescript Scratchpad to experiment with this scenario; I couldn't replicate any failures using these methods. However, please note that my fake "_teamsService" version is already initialized.

You can explore the typescript example here. Feel free to replace the function definition with any of the mentioned three ways, and you should see no issues.

Answer №3

Have you checked the source of this._userService? It seems like it may not have been properly set up.

Could it be that you overlooked injecting it into the constructor?

Answer №4

When you follow these steps:

private loadTeams = function(){
  // the reference here is to the function itself
}

What you need to do instead is:

private loadTeams() {
  // now the reference is to the instance of the class
}

An alternative approach is to bind this in the constructor like so:

constructor(/* insert dependencies here */) {
  this.loadTeams = this.loadTeams.bind(this)
}
private loadTeams = function(){
  // now the reference is to the instance of the class
}

Although, I'm not entirely convinced that this is the root of your issue.

If this was indeed the problem, then this._userService would be undefined and you'd encounter a null pointer error when trying to call undefined.getUserByToken(token)

Just a heads up, I've mentioned this 16 times in this post, did you catch that?

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

Retrieving data from Redis cache may not always yield the exact same data

I have been working on creating a small Express app that retrieves data from a PostgreSQL query and caches the result in a Redis database. Here is my approach: app.get('/query_tile/:z/:x/:y', async (req: Request, res: Response) => { const ...

Exploring Objects within an array using Angular loops

Hey there, I'm currently working on an Angular project and I need to retrieve the userName of the user for each comment that is posted. These entities are coming from my Spring Boot project. Is there a way to access the username for every comment? He ...

Changing the Class of an Element in a Different Component with Angular 2+

Currently in a project utilizing Angular 4, I have implemented two components: app.component and other.component Within app.component.html, there exists a div with the name attribute myClass. <div class="myClass"></div> In the other.componen ...

Encountering an error in resolving a dependency while attempting to run 'npm

I'm working with Angular version 13 at the moment. Encountered some errors when trying to execute the npm install command. Any suggestions on how to resolve these issues? > npm install npm ERR! code ERESOLVE npm ERR! ERESOLVE could not solve npm ...

Getting the number of ticks from an rxjs Observable is a simple process that involves extracting

Is there a way to track how many times this observable has run? this.clock = Observable.interval(1000).map(function(value){ if(value == 0){ return value * 100 / 60; } return value * 100 / 60; }).take(61); I would like to kno ...

Tips on how to connect with ngFor

I have been working on an application to display various events, but I am encountering an issue. Whenever I load the webpage, it appears empty and the console throws an error saying 'Can't bind to 'ngForEvent' since it isn't a know ...

Refreshing an Angular page with parameterized routes on IIS results in a blank page

In an effort to resolve the 404 error that occurs when refreshing a page on my Angular application, I made modifications to the web.config file within the website folder on IIS. The code snippet added is shown below: <rule name="AngularJS Routes&qu ...

Testing the GET method in an Angular service: A guide

I'm currently facing an issue with my service method and unit test setup. Despite writing a unit test for the getter method, the coverage report indicates that this method is not covered. I would appreciate any advice on what might be going wrong in m ...

Steps to modify the Angular Universal entry file to app.js and relocate it to the root directory of the app

Currently, I have an Angular Universal SSR application running on node with the latest versions of Angular and Universal as of 21/01/2021. My hosting provider allows me to host my nodejs apps on a shared cPanel, but they only accept the entry file named a ...

File or directory does not exist: ENOENT error encountered when attempting to access 'distrowserindex.html'

Upon executing ng deploy --preview, an error is encountered: Error: ENOENT: no such file or directory, open 'dist\index.html' at Object.openSync (fs.js:457:3) at readFileSync (fs.js:359:35) Despite attempting various online tutorial ...

Transforming an array of elements into an object holding those elements

I really want to accomplish something similar to this: type Bar = { title: string; data: any; } const myBars: Bar[] = [ { title: "goodbye", data: 2, }, { title: "universe", data: "foo" } ]; funct ...

Having trouble with Ionic 4 navigation not triggering after a single click, requiring multiple clicks to navigate

I have a long list of items, around 40 in total, that load a page describing each item with photos, URLs, and other content. However, I find that I need to click two to three times before reaching this page. I suspect that the excessive use of HTML compone ...

Obtaining the created by and modified by values from a SharePoint list can be achieved using Angular's http get method

I have received a response that includes the Created date and Modified date, but the Created by and Modified by information is missing. this.http.get(this.baseurl + "_api/web/lists/getByTitle('mylist')/items?$select ID,Created,CreatedBy, ...

I'm having trouble displaying my Angular project on Localhost:4200

I am facing an issue with my localhost:4200 where it is not displaying anything from my project. It was working fine before but after making some changes like generating a new component and modifying it, the page appears blank now.see image here see image ...

Observing the Transformation When Employing *ngIf or *ngSwitchCase in Angular 2

Can someone lend a hand? I've run into an issue where my custom JavaScript function is not working after using *ngIf or *ngSwitchCase to change the view. Any suggestions on how to resolve this would be greatly appreciated. ...

Issue with form using "target=_blank" to open PDF in web application home screen not functioning properly

I am encountering an issue in my Angular application where a form with target="_blank" successfully returns a PDF upon submission, but when accessed from the homescreen icon of the web-app in Android/Chrome, the new window opens blank without displaying th ...

Angular's promise is incompatible with the type ts2322 and cannot be assigned

Struggling to implement a login feature in Angular, encountering an error related to promises: "Type 'Promise<ApiResponse<UserLogged> | undefined>' is not assignable to type 'Promise<ApiResponse<UserLogged>>&apos ...

How is it possible for a TypeScript function to return something when its return type is void?

I find the book Learning JavaScript to be confusing. It delivers conflicting information regarding the use of void as a return type in functions. const foo = (s: string): void => { return 1; // ERROR } At first, it states that if a function has a re ...

Ways to remove newly added tasks using JavaScript function?

I have an existing list of li elements in my HTML that can be deleted using JavaScript. However, whenever I add a new li, the delete function no longer works on the newly added item. I suspect the issue lies within the current implementation of the for loo ...

Checking for String Const Type in TypeScript

In my code, I have a custom type called Admin with two possible values: 'ADMIN' or 'AGENT'. There is a function that retrieves the user role from local storage: return localStorage.getItem('role'); I am looking to verify if ...