首页 > 解决方案 > 为什么我的变量被认为超出范围?

问题描述

我目前正在使用 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);
    });
  }
}

标签: angulartypescriptscope

解决方案


当您使用经典函数时, 的值this取决于函数的调用方式。它或多或少会查看调用它的对象以确定是什么this

箭头函数查看函数的外部范围以确定是什么this

因此,在您的情况下,您希望this成为外部范围,即 DataService。因此,使用箭头函数会忽略调用函数的对象,而是查看函数在哪里定义的作用域。

您可以在此处阅读更多示例。


推荐阅读