Unable to reach the module within an Angular promise

Whenever I try to utilize a service, specifically TokenService with its method getToken() that returns the string "totototok", I encounter an issue when calling it within a promise. The error message displayed is:

core.js:15723 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'tokenService' of undefined TypeError: Cannot read property 'tokenService' of undefined

Below is a simple example highlighting the problem at hand.

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})

export class TokenService {

  token : string;

  constructor() {
    this.token="tototototok" 
  }

  getToken(){
    return this.token;
  }
}
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { TokenService } from '../services/token.service';

@Component({
  selector: 'app-testpromise',
  templateUrl: './testpromise.component.html',
  styleUrls: ['./testpromise.component.scss']
})
export class TestpromiseComponent implements OnInit {

  constructor(private tokenService : TokenService) { }

  ngOnInit() {
  }

  first(){


    return new Promise(function(resolve,reject){

      console.log(this.tokenService.getToken());

    })
  }

}

Any suggestions on how I can resolve this issue?

Answer №1

One way to access it is by utilizing the arrow function for lexical scoping.

return new Promise((resolve, reject) => {
  console.log(this.tokenService.getToken());
})
  • Explore more on arrow functions here

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

Proceed the flow of event propagation using the react-aria button element

In the react-aria library, event bubbling for buttons is disabled. I am facing an issue where my button, which is nested inside a div that acts as a file uploader, does not trigger the file explorer when clicked due to event bubbling being disabled. How ...

Tips on maintaining consistent language between two Angular components for a father and son relationship

I am facing an issue with language selection in my Angular project. I have two components, home.components (father) and room.component.ts (son), which support both English and Spanish languages. When I switch the language in the room component and then na ...

Issue with conflicting namespaces warning when compiling an Angular 9 project with ng-packagr using Typescript

I'm trying to pinpoint the root cause of this problem, and I suspect it may be related to Typescript. However, it could also involve ng-packagr or Angular. This issue only arose after upgrading to Angular 9. Upon building my production environment, I ...

What is the best way to showcase the outcome of a function on the user interface in Angular 2?

The code snippet below was originally in my .component.html file: <div class="someContainer"> <div class="text--bold">Display this please:</div> <div>{{ myObject.date ? '2 Jun' : 'Now' }}</div&g ...

The design features an Ionic grid with two columns: the left column is fixed in place, while the right column is

I seem to be struggling to locate proper documentation on the functionality of this feature. My main objective is to modify the code below so that the left column remains fixed (or potentially scrolls independently) while the right column scrolls. This p ...

When a function is passed as an argument in Typescript, it may return the window object instead of the constructor

I'm still getting the hang of typescript, and I've come across a situation where a function inside a Class constructor is calling another function, but when trying to access this within sayHelloAgain(), it returns the window object instead. With ...

How come the path alias I defined is not being recognized?

Summary: I am encountering error TS2307 while trying to import a file using an alias path configured in tsconfig.json, despite believing the path is correct. The structure of directories in my Angular/nx/TypeScript project appears as follows: project |- ...

Using *ngFor alters the positioning of components

After implementing a flexbox container class to align my components horizontally, I noticed that when using input properties and a loop, they are displayed stacked vertically instead. <div class="flexbox-container" > <app-card></ ...

Creating adaptable rows and columns with Angular Material's data table feature

My approach to rendering dynamic rows and columns using a basic table was successful: <tbody> <tr *ngFor="let row of data"> <td *ngFor="let val of row"> {{ val }} </td> </tr> </tbody> </ ...

Having trouble centering an icon in a cell within AG Grid?

I am struggling with aligning my checkmarks within the cells of my AG Grid. Currently, they are all left aligned but I need them to be centered. Adjusting the alignment for text is not an issue, but I can't seem to center the material icons. It appear ...

Typescript types for the Google Calendar API

Is there anyone out there who can confirm whether the google Calendar API (via the npm package googleapis) for node.js or browser supports types that can be utilized in TypeScript? This would allow for a more strongly typed approach in projects using node ...

The data attribute in Cypress does not appear in the Angular Document Object Model

I've been attempting to integrate Cypress into my Angular project using data-cy attributes, but the behavior is quite inconsistent. Some areas display the attribute in the DOM, while others do not. For instance, in the following example, the data-cy ...

Changing the text of a button using ngClass in Angular's toggle functionality

Is there a way to modify the text of a toggled button class in Angular using Bootstrap? Currently, I have this code to toggle the class: html <!-- toggle button --> <button type="button" class="btn btn-primary mt-3 ml-3" (click)="status=!status ...

Issue with sending props to TypeScript React component

Having a challenge with styling a simple button component using styled components. When trying to send a prop to the component, TypeScript throws an error saying "No overload matches this call". App.tsx import React from 'react'; import Button ...

Encountering a SonarQube error message stating "Unnecessary 'undefined' should be removed" when using "undefined" as a function argument

When calling a function, I have been passing "undefined" multiple times as a parameter. However, the SonarQube report is flagging an error stating "Remove this redundant undefined". https://i.stack.imgur.com/YhOZW.png It should be noted that the function ...

Using Angular to incorporate an attribute directive into an element within index.html

I have included some script tags containing asynchronous JavaScript libraries in my index.html file. I want to apply an attribute directive that will control their "activation" by changing the type attribute from "text/plain" to "text/javascript" once the ...

Using Typescript to define Vuex store types

Attempting to create a TypeScript-friendly Vuex store has been quite the challenge. Following instructions outlined here, I've encountered an issue where accessing this.$store from a component results in a type of Store<any>. I'm strugglin ...

Incorporate animated SVG directly into Vue templates without using any additional enclosures

I need to incorporate dynamic SVG code into my <template> without using v-html or any wrapper around it. The desired end result should look like the following, but template does not support v-html to achieve this. If there is a way to accomplish thi ...

Converting numerical values into currency format using Angular

Can anyone provide guidance on how to format a number received from the API as currency in Angular 15? This is what my HTML currently looks like: <thead class="fixed-top cabecalhoTabela"> <mat-card-header> & ...

Interface with several generic types

In an attempt to create a parser that can parse data fields and convert them into a complete form for display purposes, the fields property plays a crucial role. This property will define each field in a JSON data array that the client receives from the ur ...