gpt4 book ai didi

javascript - Typescript 组件中的“this”与 Angular2 中的 ES5

转载 作者:行者123 更新时间:2023-11-28 18:38:51 25 4
gpt4 key购买 nike

因此,我一直在尝试将我的 Angular2 应用程序从 Typescript 转换为 ES5,并尝试使它们都以类似的方式运行。我遇到的问题是让 this.people 在 ES5 版本中更新。

当我在构造函数中与在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._personService.getUsers(term)
.then(function(people) {
//Problem is with the 'this' below:
this.people = people;
}.bind(this));

(这个上下文是错误的。在 ES6 中,你有箭头函数可以解决这个问题)

关于javascript - Typescript 组件中的“this”与 Angular2 中的 ES5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36485805/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com