{ this.url = data.json().url; }); a...">

Angular 2. Http. Subscribe: "this" index

Got:

http.request('js/app/config/config.json').subscribe(data => { this.url = data.json().url; }); 

and somehow "this" points to the subscriber. I don’t know why ... because I thought the lambda of the bold arrow would catch the pointer of the parent class.

Why is that?

+5
source share
4 answers

In the screenshot: http://d.pr/i/iBa

enter image description here

You are debugging this in the console. Note that this on the console this will be relevant . When TypeScript generates an arrow function for JavaScript without ES6 (which does not have native arrow function support) this maps to _this (and other things), which means you need to view _this .

Tip

Just debug generated JavaScript while learning TypeScript. This is a TypeScript error: https://github.com/Microsoft/TypeScript/issues/2859 if you are interested.

+5
source

I found a workaround, you can try this

 http.request('js/app/config/config.json').subscribe((function (data) { this.url = data.json().url; }).bind(this)); 
+3
source

Arrow functions do not have this value of their own. The value of this inside the arrow function is always inherited from the enclosing area, in your case Subscriber .

In ES6, notice that the subscribe method gets this from its caller. An internal function is an arrow function, so it inherits this from the application area.

+2
source

ES6 Function Arrow Function to avoid creating another variable for the context. You cannot override the functions of the "this" arrows.

 http.request('js/app/config/config.json').subscribe(function(data) { this.url = data.json().url; }); 

Refer to this document: http://derickbailey.com/2015/09/28/do-es6-arrow-functions-really-solve-this-in-javascript/

+1
source

Source: https://habr.com/ru/post/1240403/


All Articles