英文:
TypeError: Cannot read properties of undefined (reading 'api_url')
问题
我正在尝试通过用户的电子邮件地址验证用户是否存在,以便使用AngularJS重置密码。
private api_url = AppSettings.API_ENDPOINT + 'user-info/email_validate';
......
async function sendRequest<T>(email:string):Promise<T>{
// console.log(this.api_url);
const res = await fetch (this.api_url, {
method:"post",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({
email: email,
})
}).then((res) => {
if(!res.ok){
console.log("ERROR");
return res;
}
return res;
})
return res.json();
}
尝试后,我的文件输出如下:
ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'api_url')
TypeError: Cannot read properties of undefined (reading 'api_url')
不知道该怎么办。
英文:
I am trying to validate whether the user exists via his email in order to reset password with AngularJS.
private api_url = AppSettings.API_ENDPOINT + 'user-info/email_validate';
......
async function sendRequest<T>(email:string):Promise<T>{
// console.log(this.api_url);
const res = await fetch (this.api_url, {
method:"post",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({
email: email,
})
}).then((res) => {
if(!res.ok){
console.log("ERROR");
return res;
}
return res;
})
return res.json();
}
After trying this, my file outputs are:
ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'api_url')
TypeError: Cannot read properties of undefined (reading 'api_url')
Don't know what to do.
答案1
得分: 1
你无法在典型的函数中获取this
。你可以使用箭头函数来解决这个问题。
class Demo {
private api_url = `${AppSettings.API_ENDPOINT}user-info/email_validate`;
// ....
sendRequest = async <T>(email: string): Promise<T> => {
// console.log(this.api_url);
const res = await fetch(this.api_url, {
body: JSON.stringify({
email,
}),
headers: { 'Content-Type': 'application/json' },
method: 'post',
}).then((res) => {
if (!res.ok) {
console.log('ERROR');
return res;
}
return res;
});
return res.json();
};
}
英文:
You can't get this
in a typical function. You can use the arrow function to solve it.
class Demo {
private api_url = `${AppSettings.API_ENDPOINT}user-info/email_validate`;
// ....
sendRequest = async <T>(email: string): Promise<T> => {
// console.log(this.api_url);
const res = await fetch(this.api_url, {
body: JSON.stringify({
email,
}),
headers: { 'Content-Type': 'application/json' },
method: 'post',
}).then((res) => {
if (!res.ok) {
console.log('ERROR');
return res;
}
return res;
});
return res.json();
};
}
For more information
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#this_in_arrow_functions
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论