简体   繁体   English

错误错误:在 Angular 项目上找不到支持类型为“object”的 object“[object Object]”的差异

[英]ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object' on Angular Project

So, I'm trying to get a json from my backend, but I'm failing to do so.所以,我试图从后端获取 json,但我没有这样做。 This is my code:这是我的代码:

averomar.services.ts averomar.服务.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

export interface Quartos {
  _id: string;
  Hotel: string;
  Quarto: string;
  Número: string;
  PreçoBaixa: string;
  PreçoAlta: string;
  Servicos: string;
}

@Injectable({
  providedIn: 'root'
})

export class AveromarService {
  baseURL = 'http://localhost:3055';

  constructor(private http: HttpClient) { }

  getRoomsAveroMar() {

    return this.http.get<Quartos[]>(this.baseURL+'/quartos/averomar')
      .pipe(
        retry(3), // retry a failed request up to 3 times
        catchError(this.handleError) // then handle the error
      );

  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    // return an observable with a user-facing error message
    return throwError(
      'Something bad happened; please try again later.');
  };
}

averomar.component.ts averomar.组件.ts

import { Component, OnInit, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Quartos, AveromarService } from '../averomar.service';

@Component({
  selector: 'app-averomar',
  templateUrl: './averomar.component.html',
  styleUrls: ['./averomar.component.css']
})

@Injectable()
export class AveromarComponent implements OnInit {

  quartos: Quartos[];

  servicosarr: string[];

  constructor(private AveromarService: AveromarService) { }

  showConfig() {
    this.AveromarService.getRoomsAveroMar()
      .subscribe(
        (data: Quartos[]) => {
          this.quartos = { ...data };
          console.log(this.quartos);
        }
      );
  }

  getServicos(quarto){
    this.servicosarr = quarto.Servicos.split(",");
  }

  public ngOnInit() {
    this.showConfig();
    console.log("Init done! ;)");
  }


}

and on the html在 html 上

  <div class="column leftborder" *ngIf="quartos">
<h2>Informações sobre os nossos Quartos:</h2>
<div class="row">
  <div class="column" *ngFor="let quarto of quartos">
    <h2>{{quarto.Quarto}}</h2>
    <li *ngFor="let servico of getServicos(quarto)">{{servico}}</li>
  </div>
</div>

The json that the backend returns is like this:后端返回的json是这样的:

[{"_id":"5ebf1383dec3c204c48457a3","Hotel":"A Ver o Mar","Quarto":"Standard","Número":"3","PreçoBaixa":"180","PreçoAlta":"270","Servicos":"Telefone,Wi-fi gratuito,Ar condicionado,Televisão LED,Canais por cabo,Mini-bar,Casa de banho privativa com telefone,Secador de cabelo,Espelho de maquilhagem,Produtos de higiene pessoal gratuitos,Fechadura eletrónica de segurança,Roupão e chinelos,Maquina de café"},{"_id":"5ebf1429ebf36e4e80a55d4a","Hotel":"A Ver o Mar","Quarto":"Suite","Número":"1","PreçoBaixa":"270","PreçoAlta":"350","Servicos":"Telefone,Wi-fi gratuito,Ar condicionado,Televisão LED,Canais por cabo,Cofre,Casa de banho privativa com telefone,Secador de cabelo,Espelho de maquilhagem,Produtos de higiene pessoal gratuitos,Fechadura eletrónica de segurança,Sala-de-estar,Roupão e chinelos,Maquina de café"}]

This is the error from the console:这是来自控制台的错误: Chrome 控制台

And this is the json pretified:这是美化的 json: Json美化

I already tried many different things that I found here, but nothing solved the issue.我已经尝试了在这里找到的许多不同的东西,但没有解决问题。 I'm not sure if I should read it as a array to start with, but it's my first angular project, so I'm a bit confused on how this all works.我不确定是否应该将它作为一个数组来阅读,但这是我的第一个 angular 项目,所以我对这一切的工作原理有点困惑。

Thank you for your help!谢谢您的帮助!

This code is creating a new object because you spread the response array 'data' inside the { } this.quartos = {...data };此代码正在创建一个新的 object,因为您将响应数组“数据”分布在 {} this.quartos = {...data };

You must spread an array inside [ ] like this.您必须像这样在 [ ] 内展开一个数组。 this.quartos = [...data ]; this.quartos = [...数据];

If you want to see a compile error try this.如果你想看到编译错误,试试这个。 this.quartos = {...data } as Quartos[]; this.quartos = {...data} 作为 Quartos[];

Since this is an http service request you don't need to spread it anyway.由于这是一个 http 服务请求,您无论如何都不需要传播它。 You could do this instead.你可以这样做。 this.quartos = data; this.quartos = 数据;

暂无
暂无

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

相关问题 在角度6中找不到类型为“对象”的其他支持对象“ [对象对象]” - Cannot find a differ supporting object '[object Object]' of type 'object' in angular 6 错误:找不到类型为“对象”的其他支持对象“ [对象对象]”。 NgFor仅支持绑定到Iterables - Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables 流星集合中找不到类型为“对象”的其他支持对象“ [对象对象]” - Cannot find a differ supporting object '[object Object]' of type 'object' , Error in meteor Collections 迭代数组中的数组时出错:“找不到支持 object '[object Object]' 类型为 'object' 的不同。” - Error when iterating over array within array: “Cannot find a differ supporting object '[object Object]' of type 'object'.” 错误找不到类型为“对象”的其他支持对象“ [对象对象]”。 NgFor仅支持绑定到可迭代对象,例如数组 - ERROR Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays 错误:找不到支持 object '[object Object]' 类型 'object' 的差异 - Err: Cannot find a differ supporting object '[object Object]' of type 'object' 在 Angular 8 中找不到不同的支持 object '[object Object] - Cannot find a differ supporting object '[object Object] in Angular 8 Angular 7 找不到类型为“object”的不同支持对象“[object Object]”。 NgFor 只支持绑定到 Iterables,比如 Arrays - Angular 7 Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays Angular 9 找不到支持“对象”类型的 object“[对象对象]”的不同。 NgFor 仅支持绑定到诸如 Arrays 之类的 Iterables - Angular 9 Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays 找不到类型为“object”的不同支持对象“[object Object]”。 NgFor 仅支持绑定到可迭代对象,例如数组。 [Angular 8] - Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.[Angular 8]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM