【发布时间】:2016-04-07 19:46:41
【问题描述】:
所以我一直在尝试将我的 Angular2 应用程序从 Typescript 转换为 ES5,并一直在尝试使它们都以类似的方式运行。我遇到的问题是让this.people 在 ES5 版本中更新。
当我在 constructor 与 searchFor 方法中 console.log this 时,我得到了类的范围与窗口的范围。当我在我的 Typescript 版本中 console.log this 时,它保留在 SearchComponent 中并且在两者中都是相同的。
Typescript 版本:
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。任何有关此问题的帮助或更正将不胜感激!
【问题讨论】:
标签: javascript typescript angular ecmascript-5