angular - 为什么我的变量被认为超出范围?
问题描述
我目前正在使用 Angular 9,但在访问全局变量时遇到了一些问题。当我将 ES6 回调函数传递给时,我可以访问 listOfProjects 变量,map
但是当我使用普通函数时,我收到一条错误消息Cannot read property 'push' of undefined
。我认为该变量已超出范围。我对如何解决这个问题有点迷茫。此外,如果您在我的代码中看到任何不好的做法,请随时指出它们,因为我对 Angular 还很陌生。
具有正常功能的代码:
export class DataService {
listOfProjects: Project[] = [];
API_URL: string = "API_URL";
homePageHeading: string;
constructor(private httpClient: HttpClient) { }
getProjects() {
this.listOfProjects.length = 0;
this.httpClient.get<any[]>("API_URL").pipe(
map(function mapData(res) {
this.homePageHeading = res[0].heading
res[0].projects.map( (project) =>
this.listOfProjects.push(
{
"company": project.company,
"description": project.description,
"imageUrl": this.API_URL + project.image[0].url,
"Link": project.Link
})
)
})
).subscribe(res => {
console.log(this.listOfProjects);
});
}
}
具有正常功能的代码:
export class DataService {
listOfProjects: Project[] = [];
API_URL: string = "API_URL";
homePageHeading: string;
constructor(private httpClient: HttpClient) { }
getProjects() {
this.listOfProjects.length = 0;
this.httpClient.get<any[]>("API_URL").pipe(
map((res) => {
this.homePageHeading = res[0].heading
res[0].projects.map( (project) =>
this.listOfProjects.push(
{
"company": project.company,
"description": project.description,
"imageUrl": this.API_URL + project.image[0].url,
"Link": project.Link
})
)
})
).subscribe(res => {
console.log(this.listOfProjects);
});
}
}
解决方案
当您使用经典函数时, 的值this
取决于函数的调用方式。它或多或少会查看调用它的对象以确定是什么this
。
箭头函数查看函数的外部范围以确定是什么this
。
因此,在您的情况下,您希望this
成为外部范围,即 DataService。因此,使用箭头函数会忽略调用函数的对象,而是查看函数在哪里定义的作用域。
您可以在此处阅读更多示例。
推荐阅读
- ios - iOS13: Universal Links not opening if the app was not running
- c# - 为什么这个异步方法不会导致线程死锁?
- go - Is GoLang safe to use partial cache restoration with CircleCI?
- c# - How to use class from DLL referenced by referenced DLL
- python - 403 forbidden when using OpenGraph Django
- spring-boot - 如何在@WebFluxTest 中禁用 oauth2 客户端注册?
- php - Getting maximum values from table through inner join not producing fully output
- c# - Kafka c#:自定义分区器和分配器实现
- c# - .Include 表达式不一致的EntityFramework
- spring-boot - Spring Boot Rest 模板编码