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?