2016-04-07 9 views
0

私はAngmark2アプリケーションをTypescriptからES5に変換しようとしていて、両方を同様に実行しようとしています。問題は、this.peopleをES5バージョンで更新することです。'これはTypescriptのコンポーネントとAngular2のES5との比較

私は私のsearchFor方法で対コンストラクタthisをCONSOLE.LOGとき、私は窓のスコープに対して、クラスのスコープを取得します。私がconsole.log this私のTypescriptバージョンでは、SearchComponent内にとどまり、両方で同じです。

活字バージョン:

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バージョン

(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 = {})); 

、私はコンポーネントとサービスの仕事を行うことで、いくつかの成功を収めてきましたが、私はthisに困惑ビットよha。問題のあるヘルプや修正は本当に感謝しています!

答えて

3

変更するコード:

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

(これのコンテキストが間違っているES6では、あなたがこの問題を解決するための矢印機能を持っています。)

+0

作品、おかげで全体の束に!私は「この」とスコープのコンセプトでさらにレビューする必要があると思います。 –

+1

TypeScriptの矢印関数では、この場合、 '.bind'より矢印関数を使用する方が読みやすくなります。 –

関連する問題