我意识到我在某些功能的产品如何以及具体何时在 JavaScript 中可用方面缺少一些东西。
在我的 Angular 应用程序中,为了获取用户的姓名缩写,我正在解析从 API 返回的数据,并在两个不同的函数中检索名字的第一个字母以及姓氏的第一个字母。这两个函数按预期工作,我可以在控制台中看到正确的结果:
getFirstNameFirstLetter() {
if (this.authenticationService.isAuthenticated()) {
const userObj = JSON.parse(sessionStorage.getItem('currentUser'));
const userInfo = userObj.data;
const firstName = userInfo.name.first;
const firstNameFirstLetter = firstName.trim().charAt(0);
console.log(firstNameFirstLetter);
return firstNameFirstLetter;
}
}
getLastNameFirstLetter() {
if (this.authenticationService.isAuthenticated()) {
const userObj = JSON.parse(sessionStorage.getItem('currentUser'));
const userInfo = userObj.data;
const lastName = userInfo.name.last;
const lastNameFirstLetter = lastName.trim().charAt(0);
console.log(lastNameFirstLetter);
return lastNameFirstLetter;
}
}
现在是我不完全理解的部分。当我传递这两个函数的返回值时,为了获得缩写,如下所示:
getInitials(firstNameFirstLetter, lastNameFirstLetter) {
if (this.authenticationService.isAuthenticated()) {
if (!this.firstNameFirstLetter || !this.lastNameFirstLetter) {
console.log('Names not ready!');
return;
} else if (this.firstNameFirstLetter && this.lastNameFirstLetter) {
console.log(firstNameFirstLetter + lastNameFirstLetter);
return firstNameFirstLetter + lastNameFirstLetter;
}
}
}
...我收到“名称未准备好!”每次都打印到控制台。
顺便说一句,我在 Angular 的 ngOnInit 生命周期 Hook 中运行这些函数,如下所示:
ngOnInit() {
this.getFirstNameFirstLetter();
this.getLastNameFirstLetter();
this.getInitials(this.firstNameFirstLetter, this.lastNameFirstLetter);
}
我知道这与可用时间有关,因为当我使用断点并调试传递到“getInitials()”函数的两个值时,我得到“未定义”。换句话说,该函数在运行时无法访问其他两个函数的返回值 - 因此我收到“名称未准备好!”打印到控制台。我的问题是,在架构上我缺少什么来解决此类问题?
最佳答案
所以这里发生的情况是,JavaScript 认为您没有使用 getFirstNameFirstLetter 和 getLastNameFirstLetter 的返回值,因此当它进行调用时,它不会等待该调用完成,而是继续进行下一个调用,这引入了竞争条件。如果你只是将其更改为
ngOnInit() {
let temp1 = this.getFirstNameFirstLetter();
let temp2 = this.getLastNameFirstLetter();
this.getInitials(this.firstNameFirstLetter, this.lastNameFirstLetter);
}
然后它将等待前一个函数完成,然后再调用下一个函数。
<小时/>另外,我不经常使用 const,所以我可能是错的,它可能遵循不同的作用域规则,但根据正常的作用域规则,在该函数中设置变量,它仅在该函数中可用,你会需要将其设置为
this.firstNameFirstLetter = firstName.trim().charAt(0);
在函数之外访问它。
<小时/>或者,一石二鸟,你可以这样做
ngOnInit() {
this.firstNameFirstLetter = this.getFirstNameFirstLetter();
this.lastNameFirstLetter = this.getLastNameFirstLetter();
this.getInitials(this.firstNameFirstLetter, this.lastNameFirstLetter);
}
或
ngOnInit() {
let firstNameFirstLetter = this.getFirstNameFirstLetter();
let lastNameFirstLetter = this.getLastNameFirstLetter();
this.getInitials(firstNameFirstLetter, lastNameFirstLetter);
}
取决于您是否再次需要变量或仅用于该函数。
关于javascript - Angular 应用程序中函数运行时传递的值不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44142831/