Tips on resolving the error message "this.accountService is not defined"

I am new to Angular and JHipster and need help solving a problem. I have not made any changes to the code, it is still using JHipster's default code for login.

Stack trace:

TypeError: this.accountService is undefined Stack trace: LoginService.prototype.logout@webpack-internal:///./src/main/webapp/app/core/login/login.service.ts:33:9 NavbarComponent.prototype.logout@webpack-internal:///./src/main/webapp/app/layouts/navbar/navbar.component.ts:49:9 View_NavbarComponent_30/<@ng:///NgrkAppModule/NavbarComponent.ngfactory.js:1470:23

core/login/login.service.ts:

import { AccountService } from 'app/core/auth/account.service';

--------------------------------------------------

constructor(private accountService: AccountService)

--------------------------------------------------

    login(credentials, callback?) {
        const cb = callback || function() {};

        return new Promise((resolve, reject) => {
            this.authServerProvider.login(credentials).subscribe(
                data => {
                    this.accountService.identity(true).then(account => {
                        resolve(data);
                    });
                    return cb();
                },
                err => {
                    this.logout();
                    reject(err);
                    return cb(err);
                }
            );
        });
    }


    logout() {
        this.authServerProvider.logout().subscribe();
        this.accountService.authenticate(null);
    }

core/auth/account.service.ts:

export class AccountService {
--------------------------------

    authenticate() {
      some code;
    }

    identity() {
      some code;
    }

--------------------------------
}

Answer №1

Encountering a scenario where the value of this is undefined is a common issue that arises when handling this improperly.

Solution

A quick solution is to implement an arrow function for logout:

logout = () => {

It might be beneficial to apply this in other areas (such as login) for future security.

Answer №2

Instead of using 'this' inside the Promise, store a reference to it outside and use that instead.

login(credentials, callback?) {
    let self = this;
    const cb = callback || function() {};

    return new Promise((resolve, reject) => {
        self.authServerProvider.login(credentials).subscribe(
            data => {
                self.accountService.identity(true).then(account => {
                    resolve(data);
                });
                return cb();
            },
            err => {
                self.logout();
                reject(err);
                return cb(err);
            }
        );
    });
}

Don't forget to include @Injectable() in your AccountService class:

 @Injectable()
export class AccountService

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 Angular to transform a JSON GET response into a class with methods

Essentially, I am working with an Angular component that has a variable called DashboardConfiguration which is set to an Observable. This Observable is obtained from a resolver that utilizes a service to make a GET request for a JSON object. The issue lie ...

What steps should I take to display the outline of an Angular Material Icon in my Angular application?

Currently, I have <mat-icon>info<mat-icon> The result is the info icon with a filled color. However, my intention is to display just the outline of the icon. How can I achieve that? The specific icon I am looking for can be found at https:/ ...

Unable to retrieve headers from extended Express.Request type

Currently, I am attempting to enhance the Request in Express so that it accurately represents the structure of a query. My current approach is as follows: export interface TypedRequestQuery<T> extends Express.Request { query: T; } While this met ...

Issue with starting Android Studio's emulator

I'm facing an issue with my emulator not launching the AVD. When I try to open the AVD, it starts the process but then nothing happens. There are no errors, and in the task manager, I can see processes like adb.exe and emulator.exe running. This probl ...

Types with conditions but no common parameter

I am looking to define my props as either type A or B. For instance export default function App() { type Checkbox = { type: "checkbox"; checked: boolean; }; type Dropdown = { type: "dropdown"; options: Array<an ...

Angular 2's ngModel feature allows for easy data binding and manipulation, particularly

I currently have an array of objects structured like this... this.survey = [ {id: 1, answer: ""}, {id: 2, answer: ""}, {id: 3, answer: ""}, {id: 4, answer: ""}, {id: 5, answer: ""}, {id: 6, answer: ""}, {id: 7, a ...

React/Typescript/VScode - a '.tsx' extension cannot be used at the end of an import path

I have successfully converted a series of React projects to TypeScript, but I am encountering a specific issue with one non-webpack project. The error I am facing is 'an import path cannot end with a .tsx extension'. For example, this error occur ...

Issue with remote URL mismatch when attempting to upload to Git using angular-gh-pages

I have just completed transitioning my project to use an angular workspace and now I am looking to deploy my demo application using angular-gh-pages. The repository link is https://github.com/Gillardo/ngx-bootstrap-datetime-popup In my package.json, I hav ...

VSCode mistakenly detecting Sequelize findOne and findAll return type as any inferences

I have a model defined using Sequelize as shown below: import { Sequelize, Model, BuildOptions, DataTypes } from 'sequelize'; interface User extends Model { readonly id: string; email: string; name: string; password_hash: string; reado ...

Modifying an element's value according to user input: Step-by-step guide

Within my dropdown menu, there is a single option labeled "Others". Upon selecting this option, a textbox appears allowing me to input custom text. Is it possible to dynamically update the value of the <option value="Others">Others</option>, ...

Here's a method to extract dates from today to the next 15 days and exclude weekends -Saturday and Sunday

Is there a way to generate an array of dates starting from today and spanning the next 15 days, excluding Saturdays and Sundays? For example, if today is 4/5/22, the desired array would look like ['4/5/22', '5/5/22', '6/5/22' ...

Encountering a snag in Angular 2 while attempting to utilize Publish and Connect for generating a Hot observable

I am attempting to create a Hot observable using the RxJS API in Angular 2, inspired by a similar example in http://jsbin.com/fewotud/3/edit?js,console However, when I try to use "Publish," the debugger indicates that the Publish function is undefined. So ...

Awaiting server token before executing HttpInterceptor in Angular 2+

I understand that a similar question may have been asked before, but after going through all the available resources, I am still unable to find a solution to my problem. My issue lies in the fact that HttpIntercept.intercept needs to return next.handle(re ...

Angular 2/NPM: setting up a new directory with all the necessary files for running the application

I'm feeling a bit frustrated, but I'm giving it a shot anyway. Our goal is to create a TypeScript Angular 2 hello world app that we can use as the front end for a Spring app. Currently, we're using the Angular 2 quickstart as our foundation ...

Proper positioning of try/catch block in scenarios involving delayed async/await operations

For the past six months, I have been utilizing async/await and have truly enjoyed the convenience it provides. Typically, I adhere to the traditional usage like so: try { await doSomethingAsync() } catch (e) {} Lately, I've delved into experimenti ...

Enhancing user experience with angular cdk drag & drop feature through click event activation instead of traditional dragging

Angular CDK drag and drop: Is there a way to move an item to the done list directly with a click event instead of dragging it? An example of this functionality can be seen on the 'jotform' site where clicking on an item in the left section autom ...

What is the most effective method for declaring callbacks on objects in Typescript?

I am currently working on a sidebar menu component that is connected to a service holding items in the menu. This allows multiple sources to make alterations to the menu as needed. Each item in the menu currently follows the SidebarItem interface: export ...

A rule enforced when the selector does not align with the criteria

Within a larger project, I am utilizing a component library that includes the following directive: @Directive({ selector: 'bs-navbar-item > li > a' // Below selector doesn't work well either (does not select the github link) // s ...

Error encountered: "Unable to locate module 'typescript-Collections' when modifying the module to "umd" or "amd" in the tsconfig.json file."

I recently upgraded to VS17 Enterprise and encountered an issue when trying to import the TypeScript Collections library from GitHub. After following the instructions on their page, I realized that changing the module option in my tsconfig.json file to eit ...

What steps can I take to resolve the problem of my NativeScript app not running on android?

When I entered "tns run android" in the terminal, the default emulator API23 launched but my app didn't install. Instead, an error occurred. This is different from when I run it on the IOS simulator, which runs smoothly without any errors. The nati ...