【问题标题】:Can't access to module in promise Angular [duplicate]无法访问 Promise Angular 中的模块 [重复]
【发布时间】:2019-03-28 01:16:48
【问题描述】:

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

core.js:15723 ERROR 错误:未捕获(承诺中):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());

    })
  }

}

我该如何解决这个问题?

【问题讨论】:

  • 使用箭头函数

标签: angular typescript promise


【解决方案1】:

您应该能够通过使用箭头函数来访问它以获取词法范围。

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

【讨论】:

  • 非常感谢!!!!现在它起作用了!为什么它适用于箭头函数而不是我的函数?
  • 您可以在此处阅读有关范围的更多信息medium.com/tfogo/…
猜你喜欢
  • 2014-08-21
  • 2018-03-20
  • 1970-01-01
  • 2016-12-24
  • 1970-01-01
  • 2018-08-29
  • 1970-01-01
  • 2020-06-04
  • 2015-11-05
相关资源
最近更新 更多