0

When I want to use a service, here TokenService with a method getToken() which return a string "totototok", when I call it in a promise, I can't get the answer. The error is :

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

Just below, it's an easy example just to show you the problem.

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());

    })
  }

}

How can I solve this problem ?

Mo0nKizz
  • 149
  • 7

1 Answers1

0

You should be able to access it by using the arrow function to get lexical scoping.

return new Promise((resolve,reject) => {
  console.log(this.tokenService.getToken());
})
  • Thank's a lot !!!! Now it works ! Why does it work with the arrow function and not with my function ? – Mo0nKizz Mar 27 '19 at 17:25
  • You can read more about the scope here https://medium.com/tfogo/advantages-and-pitfalls-of-arrow-functions-a16f0835799e –  Mar 27 '19 at 17:27