【问题标题】:Type 'Observable<client[]>' is not assignable to type 'NgIterable<any> | null | undefined'类型 'Observable<client[]>' 不可分配给类型 'NgIterable<any> |空 |不明确的'
【发布时间】:2022-02-02 17:58:44
【问题描述】:
<!--client component.html-->
  <div *ngFor="let client of clientss">
  <h3>{{client.name}}</h3>
  </div>
/***client services****/
getclients() {
  return this.http.get<client[]>(`https://jsonplaceholder.typicode.com/users`);
}


    //client.component.ts
    import { Component, OnInit } from '@angular/core';
    import { Observable } from "rxjs";
    import { ClientsServicesService } from 'src/app/services/clients-services.service';
    import { client } from './client';
    
    @Component({
      selector: 'app-api-clints',
      templateUrl: './api-clints.component.html',
      styleUrls: ['./api-clints.component.css']
    })
    export class ApiClintsComponent implements OnInit {
      clientsApi:any=[]
    
      clientss!:Observable<client[]>;
    
      constructor(private clientervicss:ClientsServicesService) { }
    
      ngOnInit() {
    
        this.clientss = this.clientervicss.getclients();
    }
    }
    **//client interface**
    export interface client {
      id: number;
      name: string;
      email: string;
    }

我正在尝试运行上面的代码但出现错误 类型 'Observable' 不可分配给类型 'NgIterable |空 |不明确的'。 22

~~

src/app/components/api-clints/api-clints.component.ts:8:16 8 templateUrl: './api-clints.component.html', ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 组件ApiClintsComponent的模板出错。

【问题讨论】:

  • 我认为你应该在 .html 中使用异步管道来获取数据。

标签: angular typescript


【解决方案1】:

您将客户端分配给 observable,您必须订阅它;

this.clientervicss.getclients().subscribe(clients => {
this.clientss = clients;
});

【讨论】:

  • 也必须更改clientss类型然后;)
  • 就像 Mateusz 指出的那样使用异步管道。
  • @ABOS 都有效。取决于 OP 希望对他的客户做什么。
  • @Random,我并不是说答案是错误的——对于像 OP 这样的简单情况,异步就足够了,除非 OP 需要更复杂的用例。
  • 感谢大家的努力。我用了管道,问题就解决了。我很高兴从您的经验中受益
【解决方案2】:

解决方案:

  <div *ngFor="let client of (clientss | async)">
    <h3>{{client.name}}</h3>
  </div>

解释:

clients 是一个 observable,你必须订阅它,才能获得它的值,它是一个 ngIterable | null | undefined 并且被 ngFor 接受

注意: client.component 所在的模块必须包含 imports CommonModule 或导入它的模块。

【讨论】:

  • 错字'clientss' -> 'clients'。此外,带有 client.component 的模块不一定要将 CommonModule 作为导入。如果它在 AppModule 中怎么办?还是图书馆?整个最后一句话与问题完全无关,真的。
  • 你知道AppModule 存在于他的项目中吗?我有提到任何 AppModule 吗?组件不能在模块中吗?该模块是否必须导入 CommonModule 或导入 CommonModule 的模块才能使异步管道正常工作? angular.io/api/common/AsyncPipe你的语气是邓宁-克鲁格曲线的顶峰之一
  • 大声笑,锅/水壶,嗯? ;) 但是鉴于 OP 说他们运行该项目并遇到错误,我很确定他们有一个主(App)模块。
  • 我宁愿提到 commonModule 是 asyncPipe 工作所必需的,而不是假设他们已经导入了它(可接受的反馈是,在导入中我们必须有 CommonModule 或导入它的模块)
猜你喜欢
  • 2022-07-28
  • 2021-08-15
  • 1970-01-01
  • 2018-08-14
  • 2017-08-12
  • 2018-08-30
  • 1970-01-01
  • 2021-09-23
  • 2020-05-28
相关资源
最近更新 更多