我的代码看起来是这样的,但是现在我把它放入Typescript类中,它给了我一个错误,说"不能读取未定义的属性角色"。
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.$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'
})
});