cannot get 'this' of component inside subscribe function
<p>My question is quite similar to these, but i did not solve my problem;</p>

<p><a href="https://stackoverflow.com/questions/36688955/cannot-access-to-this-of-component-in-subscribe-function">cannot access to this of component in subscribe function</a></p>

<p><a href="https://stackoverflow.com/questions/37362178/this-scope-in-typescript-callback-function">&#39;this&#39; scope in typescript callback function</a></p>

<p><a href="https://stackoverflow.com/questions/38148701/cannot-access-component-variables-in-subscribe-when-using-chrome-inspector">Cannot Access Component Variables in Subscribe when using chrome inspector</a></p>

<p><a href="https://stackoverflow.com/questions/34647449/unable-to-get-component-variables-inside-a-rxjs-subscribe-function?noredirect=1&amp;lq=1">unable to get component variables inside a RxJS subscribe() function</a></p>

<p>Here is my typescript component class:</p>

<pre><code>export class Test{
     x: string;
}

export class TestComponent implements OnInit{
     test: Test;

     constructor(private testService: TestService){}

     ngOnInit(){
          this.testService.getTest()
               .subscribe((res) =&gt; { this.test = res.test;}, ...);
          console.log(this.text.x) //it becomes undefined
     }
}
</code></pre>

<p>I am using gulp-typescript, and outputs are like these;</p>

<pre><code>//when targeting es6

let testComponent = class TestComponent ... {
     constructor(testService){
          this.testService = testService;
     }

     ngOnInit(){
          this.testService.getTest()
               .subscribe((res) =&gt; {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)
     }
}())
</code></pre>

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

<pre><code>EXCEPTION: Error: Uncaught (in promise): TypeError: Cannot read property 'x' of undefined
</code></pre>

<p>When I log the <code>this.test</code>, it is <code>undefined</code>. My TestService is injected properly, request come to my api and <code>res.test</code> includes what i need but i cannot use with <code>this.test</code> 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 compatibility etc., es5 or es6?</p>