Search code examples
javascriptangularangular11

What causes the "Cannot find name" error in this Angular 11 application?


I am working on an Angular 11 application.

In the service UserService I have:

import { Injectable, OnDestroy } from '@angular/core';
import { UserModel } from '../path/to/UserModel';

export class UserService implements OnDestroy {

    public isActiveUser: boolean = false;

    public checkUserStatus(user: UserModel) {
        return this.isActiveUser;
    }

}

I use the above service in a component, like this:

import { UserService } from '../path/to/user-service.service';
    
export class UserComponent implements OnInit {

    public isActiveUser: boolean;

    public checkUserStatus() {
        this.isActiveUser = this.UserService.checkUserStatus(user);
    }
}

The problem

In the above CompositionEvent, on the line this.isActiveUser = this.UserService.checkUserStatus(user) I get the error:

Cannot find name 'user'

What causes this error?


Solution

  • The user variable is missing in your code.

    Here are scenarios to set the user variable

    import { UserService } from '../path/to/user-service.service';
    // Import your model with below path
    import { UserModel } from '../path/to/UserModel';
        
    export class UserComponent implements OnInit {
    
        public isActiveUser: boolean;
    // Declare your user variable
    user: UserModel;
    
        public checkUserStatus() {
            this.isActiveUser = this.UserService.checkUserStatus(user);
        }
    }

    Resolve your error :)