0

I am relatively new to Angular 4.Please bear with me if the question is naive.I have the following code. I am actually firing a http call to backend to retrieve some values.

import { Component} from '@angular/core';
import { Http } from '@angular/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {

  _title = 'Coding Challenge';
  _http: Http;
  consolidateResponse: any[];

  constructor(http: Http) {
    this._http = http;
    this._title = 'Coding Challenge';
  }

  executeHttpCall() {

    this._http.get('http://xxxx')
    .subscribe(response => {
      console.log(response.json());
      this.consolidateResponse = response.json();
    });
  }

}

If I replace the arrow function present in the earlier code

response => {
          console.log(response.json());
          this.consolidateResponse = response.json();
        }

with

function(response) {
console.log(response.json());
              this.consolidateResponse = response.json();
}

It does not work. Basically the view does not get updated. If I use arrow function the view gets updated with the values retrieved from the backend server. In both cases, I can see the results if I printout the results from the server using console.log

From my understanding the arrow function is a short hand for anonymous functions, just like lambda functions in java. There should ideally have no difference.

What am I missing here ?

Jeevan Varughese
  • 2,159
  • 2
  • 15
  • 20
  • 1
    The arrow function preserves the context, when you're using a normal function, `this` refers to something else. – Titus Nov 06 '17 at 05:45
  • 1
    scope of `this` doesn't change (or localized) in arrow functions, but it does with normal function. – gurvinder372 Nov 06 '17 at 05:45

0 Answers0