【问题标题】:TypeError: Cannot read property 'forEach' of undefined AngularTypeError:无法读取未定义 Angular 的属性“forEach”
【发布时间】:2019-12-09 21:46:07
【问题描述】:
ObtenerClientes(cantidad: number): Observable<Array<Cliente>> {        
    const urlCliente = `${this.url}/?results=${cantidad}`;        
    const lstClientes: Array<Cliente> = [];    
    return this.http.get<any>(urlCliente).pipe(         
      map(clientes => {        
        (clientes.results as Array<any>).forEach((registro: any ) => {       
          lstClientes.push({   
            id: registro.CustomerID,   
            nombre: registro.ContactName,     
            companyName: registro.CompanyName      
          });           
        });        
        return lstClientes;       
      })    
    );    
  }   
}

拜托,我需要一些帮助!

【问题讨论】:

  • 这意味着它不是一个数组,所以它没有 forEach 方法。 clientes.resultsundefined,因此您的查询不会返回任何内容。

标签: angular foreach


【解决方案1】:

您应该尝试在数组上使用map 方法。

来,试试看:

ObtenerClientes(cantidad: number): Observable < Array < Cliente >> {
  const urlCliente = `${this.url}/?results=${cantidad}`;
  const lstClientes: Array < Cliente > = [];
  return this.http.get < any > (urlCliente).pipe(
    map(clientes => (clientes.results as Array < any > ).map((registro: any) => ({
      id: registro.CustomerID,
      nombre: registro.ContactName,
      companyName: registro.CompanyName
    })))
  );
}

【讨论】:

    猜你喜欢
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    • 2021-10-29
    相关资源
    最近更新 更多