无法在Promise Angular中访问模块

时间:2019-03-27 17:12:32

标签: angular typescript promise

当我想使用服务时,这里的TokenService带有方法getToken(),该方法返回字符串“ totototok”,当我在promise中调用它时,我无法获得答案。错误是:

core.js:15723错误错误:未捕获(承诺):TypeError:无法读取未定义的属性“ tokenService” TypeError:无法读取未定义的属性“ tokenService”

下面,这是一个简单的示例,仅向您显示问题。

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

    })
  }

}

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您应该能够通过使用箭头功能来访问它以获得词法作用域。

return new Promise((resolve,reject) => {
  console.log(this.tokenService.getToken());
})