【问题标题】:How to GET API data from server in Angular App?如何在 Angular App 中从服务器获取 API 数据?
【发布时间】:2021-02-26 14:57:15
【问题描述】:

我在组件中写入数据时遇到问题。我在控制台中编写对象数据,但我不知道如何从对象获取数据。 我从服务器获取到控制台的这些数据: IMAGE。我需要提取对象数据或其他内容吗?

在控制台中我有这个错误:错误类型错误:您提供了一个无效的对象,其中应该有一个流。您可以提供 Observable、Promise、Array 或 Iterable。

你知道如何解决这个问题吗?感谢您的帮助。

我的代码: app.component.ts

codeLists: CodeLists[] = [];
    
    
      constructor(
        private codeListService: CodeListService,
        private codeListsAdapter: CodeListsAdapter,
      ) { }
    
      ngOnInit(): void {
        this.getCodeLists();
      }
    
      public getCodeLists() {
        this.labService.getAllLists().subscribe(response => {
          this.codeLists = [];
          console.log(response);
          from(response).subscribe((CodeListsRaw: CodeLists) => {
              this.codeLists.push(this.codeListsAdapter.adapt(CodeListsRaw));
            });
        });
      }
    }

app.component.html

<div *ngFor="let list of codeLists">
  <mat-card>
    <mat-card-title>{{list.id}}</mat-card-title>
    <h1>{{list.name}}</h1>
  </mat-card>
</div>

code-list.service.ts

getAllLists(){
    return this.http.get<any>(environment.ApiUrl + `/api/url`);
  }

codelists.ts - 模型

export class CodeLists {
   id: string;
   name: string;
}

【问题讨论】:

    标签: angular api angular2-services


    【解决方案1】:

    其实你不需要订阅响应。

    响应是您的对象,而不是可观察的。此外,您可以使用解构。试试这个:

    public getCodeLists() {
      this.labService.getAllLists().subscribe(({ codeLists, productList }) => {
        console.log(codeLists, productList);
        codeLists.codeLists.map(codeList => // I edited this line
          this.codeLists.push(this.codeListsAdapter.adapt(codeList)));
      }
    }
    

    更多关于解构的信息:https://basarat.gitbook.io/typescript/future-javascript/destructuring

    【讨论】:

    • 感谢您的支持。控制台写这个 => ERROR TypeError: codeLists.map is not a function。如何使用 ngFor 在组件中编写项目?因为项目不会仅在控制台中写入组件。
    • 抱歉,我没有看到您将 codeLists 作为对象,然后是 codeLists 数组。我已经编辑了我的帖子。它在工作吗?它也应该适用于您的组件。
    猜你喜欢
    • 2018-03-27
    • 1970-01-01
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    • 2020-02-12
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多