2016-08-24 57 views
0

我的问题与这些非常相似,但我没有解决我的问题;无法在订阅功能中获得'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时,我应该选择哪一个?

+0

什么是“whateverItIs”。我在你的代码中没有看到你发布的内容?展开构造函数并放置一个'console.log(testService)'以确保服务正在传递/注入到构造函数中。 – Martin

+0

这只是我的Test类的任何属性,我写了'whateverItIs'的属性名称。 TestService被正确注入,我的API获取请求。 – ulubeyn

+0

您可以请包括您的测试课程的一些代码。谢谢。我只想看看真实的属性名是什么,所以我可以看到哪个对象是'undefined'。 – Martin

回答

3

在箭头函数内移动console.log语句。

ngOnInit(){ 
      this.testService.getTest() 
       .subscribe((res) => { 
       this.test = res.test; 
       console.log(this.text.x) 
      }, ...); 

    } 

如果你有你想用this.test做其他事情,那么你将不得不搬完里面太(或添加其他功能和调用从回调内部)。基本上,如果您的服务返回Observable,这意味着回调不会在您称为该功能的相同“框架”中运行。在你原来的代码,这是操作的顺序:

  1. getTest被调用时,一个AJAX操作开始
  2. 的console.log呼吁,版画不确定。
  3. 由于请求与服务器通信,用户得到的UI时间没有多少第二秒
  4. 请求结束,subscribe(() =>调用回调。 this.test已设置。
+0

这里是一个更深入的解释异步编程的链接。这不是特定于Angular2或TypeScript http://code.tutsplus.com/tutorials/event-based-programming-what-async-has-over-sync--net-30027 – Martin

+0

如果我想使用'this 。[formGroup]'内的.test.x'?当我在订阅中调用它时,出现错误,或者我应该使用模板驱动的表单而不是ReactiveForms? @ Katana314 @Martin – ulubeyn

+0

你可能想简单地用'* ngIf =“test”'包装你的表单。通过这种方式,在你的数据返回之前,表单中对'test.x'的引用不会被调用。另一种选择是使用'async'管道。或者两者的结合。 – Martin

0

“_this.componentProperty”适用于我,而不是在“subscribe()”rxjs调用中使用“this.componentProperty”。