我的问题与这些非常相似,但我没有解决我的问题;无法在订阅功能中获得'this'组件
cannot access to this of component in subscribe function
'this' scope in typescript callback function
Cannot Access Component Variables in Subscribe when using chrome inspector
unable to get component variables inside a RxJS subscribe() function
这里是我的打字稿组件类:
export class Test{
x: string;
}
export class TestComponent implements OnInit{
test: Test;
constructor(private testService: TestService){}
ngOnInit(){
this.testService.getTest()
.subscribe((res) => { this.test = res.test;}, ...);
console.log(this.text.x) //it becomes undefined
}
}
我使用一饮而尽-T ypescript和输出就像这些;
//when targeting es6
let testComponent = class TestComponent ... {
constructor(testService){
this.testService = testService;
}
ngOnInit(){
this.testService.getTest()
.subscribe((res) => {this.test = res.test;}, ...);
console.log(this.text.x)
}
}
//when targeting es5
var TestComponent = (function(){
function TestComponent(testService){
this.testService = testService;
}
TestComponent.prototype.ngOnInit = function(){
var _this = this;
this.testService.getTest()
.subscribe(function (res) { _this.test = res.test }, ...);
console.log(this.text.x)
}
}())
当我想尝试达到'this.test.x'时,我从两个输出的浏览器中得到以下错误;
EXCEPTION: Error: Uncaught (in promise): TypeError: Cannot read property 'x' of undefined
当我登录了this.test
,它是undefined
。我的TestService被正确注入,请求来到我的API并且res.test
包括我需要但是我不能使用this.test
,因为它总是未定义的。我不知道我在做什么错。有没有人可以帮助我?最后,我想问一下,在考虑浏览器兼容性,es5或es6时,我应该选择哪一个?
什么是“whateverItIs”。我在你的代码中没有看到你发布的内容?展开构造函数并放置一个'console.log(testService)'以确保服务正在传递/注入到构造函数中。 – Martin
这只是我的Test类的任何属性,我写了'whateverItIs'的属性名称。 TestService被正确注入,我的API获取请求。 – ulubeyn
您可以请包括您的测试课程的一些代码。谢谢。我只想看看真实的属性名是什么,所以我可以看到哪个对象是'undefined'。 – Martin