最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - cannot get 'this' of component inside subscribe function - Stack Overflow

programmeradmin4浏览0评论

My question is quite similar to these, but i did not solve my problem;

cannot access to this of ponent in subscribe function

'this' scope in typescript callback function

Cannot Access Component Variables in Subscribe when using chrome inspector

unable to get ponent variables inside a RxJS subscribe() function

Here is my typescript ponent class:

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 bees undefined
     }
}

I am using gulp-typescript, and outputs are like these;

//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)
     }
}())

When I want to try to reach 'this.test.x' I get the following error from browser with both outputs;

EXCEPTION: Error: Uncaught (in promise): TypeError: Cannot read property 'x' of undefined

When I log the this.test, it is undefined. My TestService is injected properly, request e to my api and res.test includes what i need but i cannot use with this.test because it is always undefined. I do not know where I am doing wrong. Is there anyone else who can help me? Finally, I want to ask that, which one should I target when considering browser patibility etc., es5 or es6?

My question is quite similar to these, but i did not solve my problem;

cannot access to this of ponent in subscribe function

'this' scope in typescript callback function

Cannot Access Component Variables in Subscribe when using chrome inspector

unable to get ponent variables inside a RxJS subscribe() function

Here is my typescript ponent class:

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 bees undefined
     }
}

I am using gulp-typescript, and outputs are like these;

//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)
     }
}())

When I want to try to reach 'this.test.x' I get the following error from browser with both outputs;

EXCEPTION: Error: Uncaught (in promise): TypeError: Cannot read property 'x' of undefined

When I log the this.test, it is undefined. My TestService is injected properly, request e to my api and res.test includes what i need but i cannot use with this.test because it is always undefined. I do not know where I am doing wrong. Is there anyone else who can help me? Finally, I want to ask that, which one should I target when considering browser patibility etc., es5 or es6?

Share Improve this question edited May 23, 2017 at 12:32 CommunityBot 11 silver badge asked Aug 24, 2016 at 8:35 ulubeynulubeyn 3,0611 gold badge21 silver badges29 bronze badges 9
  • What is 'whateverItIs'. I don't see that in your code you have posted? Expand the constructor and put a console.log(testService) to be sure the service is being passed/injected into the constructor. – Martin Commented Aug 24, 2016 at 9:10
  • It is just any property of my Test class, I wrote 'whateverItIs' insted of property name. TestService is injected properly, my api gets the request. – ulubeyn Commented Aug 24, 2016 at 9:18
  • Can you please include some of the code from your test class. Thanks. I just want to see what the real property name is so I can see which object is undefined. – Martin Commented Aug 24, 2016 at 9:24
  • 1 Ok. That would make sense to me. I would expect an error is you called console.log(this.test.x) on ngOnInit. From the code you provided this.test will not be populated until at least the next "turn" of the VM. Though you would be able to call it within the subscribe callback of you are receiving the expected data. This would be the expected behavior. The console.log() is being called BEFORE your subscribe callback. You need to move to the callback. – Martin Commented Aug 24, 2016 at 13:16
  • 1 One final thing, for browser target ES5. ES6 isn't supported on most mobile browsers yet (as of now) and only up to date desktop browsers will support ES6. Finnaly, the ES6 implementations in these browsers have not been optimized as well as the ES5 implementations. – Martin Commented Aug 24, 2016 at 13:40
 |  Show 4 more ments

3 Answers 3

Reset to default 3

Move the console.log statement inside of the arrow function.

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

     }

If you had other things you wanted to do with this.test, then you're going to have to move those inside too (or, add another function and call that from inside the callback). Basically, if you have a service that returns an Observable, that means the callback will not run in the same "frame" that you called the function. In your original code this was the order of operations:

  1. getTest is called, an AJAX operation is started
  2. console.log called, prints undefined.
  3. User gets a second of UI time with not much happening as the request municates with the server
  4. Request finishes, subscribe(() => callback is called. this.test is set.

"_this.ponentProperty" works for me instead of "this.ponentProperty" when inside a "subscribe()" rxjs call.

You can just replace your function TestComponent.prototype.ngOnInit for an Arrow function, so "this" would be accesible from your subscribe call.

发布评论

评论列表(0)

  1. 暂无评论