gpt4 book ai didi

javascript - 转换为 Typescript 后出现 "this"错误

转载 作者:行者123 更新时间:2023-11-28 01:06:31 24 4
gpt4 key购买 nike

我的代码看起来像这样,但现在我将它放入 Typescript 类中,它给了我一个错误,说“无法读取未定义的属性 Angular 色”。

    this.$http({
method: 'POST',
url: '/Token',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
data: 'grant_type=password&username=' + encodeURIComponent(userName) + '&password=' + encodeURIComponent(password),
})
.success(function (data, status, headers, cfg) {
data.roles.split(':').forEach(function (v) {
this.data.role['is' + v] = true;
v == 'Test'
})

我是否必须使用 Typescript 以不同的方式编写函数代码?我的 success() 中有两个 function,我可以用 => 替换它吗?

最佳答案

This 在本例中 this 表示运行此代码的类的实例。您绝对可以将函数转换为箭头函数 (=>) 并省略 this。代码将如下所示:

this.$http({
method: 'POST',
url: '/Token',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
data: 'grant_type=password&username=' + encodeURIComponent(userName) + '&password=' + encodeURIComponent(password),
})
.success((data, status, headers, cfg) => {
data.roles
.split(':')
.forEach((v) => {
data.role['is' + v] = true;
v == 'Test'
})
});

关于javascript - 转换为 Typescript 后出现 "this"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25015684/

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