Search code examples
javascripttypescriptangularecmascript-5

'this' in Component of Typescript vs ES5 in Angular2


So I've been trying to work through converting my Angular2 app from Typescript to ES5 and have been trying to make both of them run similarly. The problem that I'm having is getting the this.people to update in the ES5 version.

When I console.log this in the constructor versus in my searchFor method, I get the scoping of the class versus the window's scope. When I console.log this in my Typescript version, it stays within the SearchComponent and is the same in both.

Typescript Version:

import {Component} from 'angular2/core';
import {PersonService} from './person-service';

@Component({
  selector: 'search',
  properties: ['searchTerm'],
  templateUrl: `search.html`,
})

export class SearchComponent {
  searchTerm:string;
  searchPrefix:string;
  people:Person[];

  constructor(private _personService:PersonService) {
    this.searchTerm   = '';
    this.searchPrefix = "";
    this.people       = [];
    this.predicate    = 'last';
  }

  searchFor(term) {
    if (term.length < 2)
      this.people = [];
    else {
      this._personService.getUsers(term)
        .then((people)=> {
          this.people = people;
        });
    }
  }
}

ES5 Version

(function(app) {
  app.SearchComponent = ng.core
    .Component({
      selector: 'search',
      properties: ['searchTerm'],
      templateUrl: 'search.html',
      providers: [app.PersonService]
    })
    .Class({
      constructor: [app.PersonService, ng.router.Router,
        function(_personService, _router) {
          this.searchTerm = '';
          this.searchPrefix = "";
          this.people = [];
          this._personService = _personService;
          this._router = _router;
        }
      ],
      searchFor(term){
        if (term.length < 2)
          this.people = [];
        else {
          this._personService.getUsers(term)
            .then(function(people) {
              //Problem is with the 'this' below:
              this.people = people;
            });
        }
      }
    });
})(window.app || (window.app = {}));

I've had some success in making the components and services work but I'm a bit stumped on this, ha. Any help or corrections with the issue would really be appreciated!


Solution

  • Change the code to be:

     this._personService.getUsers(term)
            .then(function(people) {
              //Problem is with the 'this' below:
              this.people = people;
            }.bind(this));
    

    (The context of this is wrong. In ES6 you have arrow function which solve this problem)