首页 > 解决方案 > 打字稿非空数组返回长度为零

问题描述

目前无法理解我的以下代码的问题。任何建议或信息都非常受欢迎!

getProjects(client):string[] {
      client = client.trim();

      var tempProjects = [];
  
      // if(this.m_projects.length >= 1){
      //   this.m_projects = [];
      //   this.m_tasks = [];
      //   this.sTask = null;
      //   this.sProject = null;
      // }
      
      
      const curTaskObservable = this.afs.collection('users').doc('myFirstUser')
      .collection('clients').doc(client).collection('projects')
      .valueChanges()
      .subscribe((data:any)=>{
        data.forEach(el=>{
          if(this.m_projects.indexOf(el.name) === -1){
            this.m_projects.push(el.name);
            tempProjects.push(el.name);
          } 
        });
      });
      
      console.log("array length : " + tempProjects.length);
      console.log(" array content : " + tempProjects);
      return tempProjects;

如下所示,输出打印长度“0”,数组内容打印长度“1”。这怎么可能,有没有办法获得正确的长度值。谢谢!

控制台日志的输出

标签: angulartypescript

解决方案


subscribe((data:any)=>{
        data.forEach(el=>{
          if(this.m_projects.indexOf(el.name) === -1){
            this.m_projects.push(el.name);
            tempProjects.push(el.name);
          } 
        });
      });
      
      console.log("array length : " + tempProjects.length);
      console.log(" array content : " + tempProjects);
      return tempProjects;

数组不是空的。就是你还没有理解异步代码是如何执行的。订阅中的块可以在console.log打印数组大小之后执行。

移动console.log订阅块内部。

 subscribe((data:any)=>{
            data.forEach(el=>{
              if(this.m_projects.indexOf(el.name) === -1){
                this.m_projects.push(el.name);
                tempProjects.push(el.name);
                console.log("array length : " + tempProjects.length);
              } 
            });
          });

这将是了解异步代码如何工作的一个很好的步骤。


推荐阅读