简体   繁体   English

如何从api渲染Angular中的数据

[英]How to render data in Angular from api

I am trying to render data from an api in the 'home.component.html', but I get an error in the browser console.我正在尝试从“home.component.html”中的 api 呈现数据,但在浏览器控制台中出现错误。 The 'home.component.ts' is fetching the data correctly from my service, but I can´t manage to render it in 'home.component.html'. 'home.component.ts' 正在从我的服务中正确获取数据,但我无法设法在 'home.component.html' 中呈现它。 I may be calling it the wrong way.我可能用错误的方式称呼它。

The error I get is: Error: Error trying to diff '[object Object]'.我得到的错误是:错误:尝试区分“[object Object]”时出错。 Only arrays and iterables are allowed.只允许 arrays 和可迭代对象。

This is my 'home.component.html':这是我的“home.component.html”:

<div class="wrapper">
    <mat-card class="example-card" *ngFor="let data of datas; index as i">

        <mat-card-header>
            <div mat-card-avatar class="example-header-image"></div>
            <mat-card-title>{{ data.attributes.name }}</mat-card-title>
            <mat-card-subtitle>{{ data.attributes.publishedAt | date:'medium' }}</mat-card-subtitle>
        </mat-card-header>
        
        <img mat-card-image [src]="data.attributes.image.data.attributes.url" alt="meme">

    </mat-card>
</div>

And this is my 'home.component.ts':这是我的“home.component.ts”:


import { Component, OnInit } from '@angular/core';
import { DataService } from 'src/app/services/data.service';

// import { Meme } from 'src/app/util/interfaces';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {


  datas:any=[];
  errores:string="";
  totalLength:any;

  constructor(private data: DataService) { 
  }

  ngOnInit(): void {

    this.data.getMemes().subscribe(res=>{

     const myJSON = JSON.stringify(res); 
  
     this.datas = myJSON;

     this.totalLength = res.length;

    }, error =>{
      console.log(error);
        if(error.status == 0){
            this.errores="Código del error: "+error.status+" \n Ha ocurrido un error del lado del cliente o un error de red.";
        }else{
            this.errores="Código del error: "+error.status+"\n\n"+error.statusText;
        }
    })  

  }

}


This is the Browser console Error:这是浏览器控制台错误:

在此处输入图像描述

This is the JSON data from the api response, As you can see there is an array called 'data' with three objects inside:这是来自 api 响应的 JSON 数据,如您所见,有一个名为“data”的数组,其中包含三个对象:


{
  "data": [
    {
      "id": 1,
      "attributes": {
        "name": "black",
        "createdAt": "2023-01-17T19:18:29.362Z",
        "updatedAt": "2023-01-17T19:50:47.247Z",
        "publishedAt": "2023-01-17T19:37:56.037Z"
      }
    },
    {
      "id": 2,
      "attributes": {
        "name": "jennie",
        "createdAt": "2023-01-17T19:49:28.235Z",
        "updatedAt": "2023-01-17T19:51:07.573Z",
        "publishedAt": "2023-01-17T19:49:33.399Z"
      }
    },
    {
      "id": 3,
      "attributes": {
        "name": "pink",
        "createdAt": "2023-01-17T19:50:31.818Z",
        "updatedAt": "2023-01-17T19:50:56.444Z",
        "publishedAt": "2023-01-17T19:50:32.786Z"
      }
    }
  ],
  "meta": {
    "pagination": {
      "page": 1,
      "pageSize": 25,
      "pageCount": 1,
      "total": 3
    }
  }
}

And this is my 'data.service.ts':这是我的“data.service.ts”:


import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { environment } from 'src/environments/environment.prod';



@Injectable({
  providedIn: 'root'
})
export class DataService {

  REST_API: string ='http://localhost:1337/api/memes';

  httpHeaders = new HttpHeaders().set('Content-Type', 'application/json');

  constructor(
    private http: HttpClient
  ) {  }

  getMemes():Observable<any> {

    let API=this.REST_API;
    return this.http.get(API,{headers:this.httpHeaders}).pipe(
      map((data:any) => { 
        return data;
      }), catchError( error => {
        return throwError(error);
      })
    );

  }



}


why are you trying to pass stringified json to an array object:为什么要将字符串化的 json 传递给数组 object:

const myJSON = JSON.stringify(res);
this.datas = myJSON;

you don't need to stringify "res" object, pass res.data directly:你不需要字符串化“res”object,直接传递res.data:

this.datas = res.data;

and note that your res object doesn't have "length" property:并注意您的 res object 没有“长度”属性:

this.totalLength = res.length

you can do this:你可以这样做:

this.totalLength = res.meta.pagination.total:

and there is an invalid property call in your html view,there isn't image property in data.attributes:并且在您的 html 视图中存在无效的属性调用,data.attributes 中没有图像属性:

<img mat-card-image [src]="data.attributes.image.data.attributes.url" alt="meme">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM