【问题标题】:Angular 12 Observable<Object[]> Error when trying to perform a get methodAngular 12 Observable<Object[]> 尝试执行 get 方法时出错
【发布时间】:2022-01-25 08:05:37
【问题描述】:

我一直试图弄明白我在 Angular 12 上遇到的这个错误。

找不到“object”类型的不同支持对象“[object Object]”。 NgFor 只支持绑定到数组等 Iterables。

这是我的服务:

import { HttpClient } from '@angular/common/http';
import { Catalogo } from './../Models/Catalogo';
import { Observable } from 'rxjs';


const baseUrl = 'http://localhost:8080/'

@Injectable ({
 providedIn: 'root'
})

export class CatalogoService {

 constructor(private http: HttpClient) { }

 getAll(): Observable<Catalogo[]> {
   console.log(this.http.get<Catalogo[]>(baseUrl));
   return this.http.get<Catalogo[]>(baseUrl);
 }

这是我的组件:

import { Router } from '@angular/router';
import { CatalogoService } from './../../Services/catalogo.service';
import { Catalogo } from "./../../Models/Catalogo";
import { FormGroup, FormBuilder } from '@angular/forms';

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

export class CatalogoComponent implements OnInit {

  catalogo?: Catalogo[];
  currentCatalogo: Catalogo = {};
  currentIndex = -1;
  constructor(private catalogoService: CatalogoService) { }

  ngOnInit(): void {
    this.retrieveCatalogo();
  }

  retrieveCatalogo(): void {
    this.catalogoService.getAll()
      .subscribe(
        data => {
          this.catalogo = data;
          console.log(data);
        },
        error => {
          console.log(error);
        });
  } 

编辑:这是 HTML 部分

<div class="containter">
  <table class="table table-bordered">
    <thead>
      <tr>
        <th scope="col">Id</th>
        <th scope="col">Modelo</th>
        <th scope="col">Precio</th>
        <th scope="col">Especificacion</th>
        <th scope="col">Imagen</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let catalogo of catalogo; let i = index">
        <th scope="row">{{catalogo.id}}</th>
        <td>{{catalogo.modelo}}</td>
        <td>{{catalogo.precio}}</td>
        <td>{{catalogo.especificacion}}</td>
        <td>{{catalogo.imagen}}</td>
      </tr>
    </tbody>
  </table>
</div>

我正在关注如何将可序列化与 MEAN 堆栈一起使用的教程:

https://www.bezkoder.com/angular-12-node-js-express-mysql/ https://www.bezkoder.com/angular-12-crud-app/

但是当我尝试加载页面时,我得到了我提到的错误。

我的问题是:

为什么会这样? (我对 Angular 有点陌生)

这就是你应该如何返回一个带有 Observables 的数组吗? "this.http.get(baseUrl);"

编辑:这是服务类方法的输出:

Observable
operator: MapOperator {thisArg: undefined, project: ƒ}
source: Observable
operator: FilterOperator
predicate: (event) => event instanceof HttpResponse
thisArg: undefined
[[Prototype]]: Object
call: ƒ call(subscriber, source)
constructor: class FilterOperator
[[Prototype]]: Object
source: Observable
operator: MergeMapOperator {concurrent: 1, project: ƒ}
source: Observable {_isScalar: false, _subscribe: ƒ}
_isScalar: false
[[Prototype]]: Object
_isScalar: false
[[Prototype]]: Object
_isScalar: false
[[Prototype]]: Object

编辑:订阅方法的输出

Subscriber {closed: false, _parentOrParents: null, _subscriptions: Array(1), syncErrorValue: null, syncErrorThrown: false, …}
closed: true
destination: SafeSubscriber
closed: true
destination: {closed: true, next: ƒ, error: ƒ, complete: ƒ}
isStopped: true
syncErrorThrowable: false
syncErrorThrown: false
syncErrorValue: null
_complete: undefined
_context: null
_error: error => { console.log(error); }
_next: data => {…}
_parentOrParents: null
_parentSubscriber: null
_subscriptions: null
[[Prototype]]: Subscriber
isStopped: true
syncErrorThrowable: true
syncErrorThrown: false
syncErrorValue: null
_parentOrParents: null
_subscriptions: null
[[Prototype]]: Subscription
complete: ƒ complete()
constructor: class Subscriber
error: ƒ error(err)
next: ƒ next(value)
unsubscribe: ƒ unsubscribe()
_complete: ƒ _complete()
_error: ƒ _error(err)
_next: ƒ _next(value)
_unsubscribeAndRecycle: ƒ _unsubscribeAndRecycle()
Symbol(rxSubscriber): ƒ [_internal_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_2__.rxSubscriber]()
[[Prototype]]: Object

谢谢!

【问题讨论】:

  • 也很高兴看到 *ngFor 部分
  • 如果你能附上HTML(使用*ngFor的部分)和从API接收的示例JSON数据会更好。
  • console.log 也来自服务部分或组件。因为对我来说看起来像 http 调用返回
  • @Osakr 它来自服务。
  • 最好把订阅的console.log贴出来,看看是什么对象

标签: angular typescript http mean-stack


【解决方案1】:

让我们简化事情以使其更容易。为了简化和提高性能,我建议您使用异步管道。让我给你看看。

首先在你的component.ts中你不需要retrieveCatalogo方法,我们将存储observable并通过异步管道直接在模板中使用它。

组件:

import { Router } from '@angular/router';
import { CatalogoService } from './../../Services/catalogo.service';
import { Catalogo } from "./../../Models/Catalogo";
import { FormGroup, FormBuilder } from '@angular/forms';

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

export class CatalogoComponent implements OnInit {
  
  // We use the $ at the end of the var name as a naming convention for storing observables and subscriptions.
  catalogos$!: Observable<Catalogo[]>;
  currentCatalogo: Catalogo = {};
  currentIndex = -1;
  constructor(private catalogoService: CatalogoService) { }

  ngOnInit(): void {
    // We call the service and store the observable
    this.catalogos$ = this.catalogoService.getAll();
  }

现在在您的组件模板中,我们需要使用异步管道

...
    <tbody *ngIf="catalogos$ | async as catalogos">
      <tr *ngFor="let catalogo of catalogos">
        <th scope="row">{{catalogo.id}}</th>
        <td>{{catalogo.modelo}}</td>
        <td>{{catalogo.precio}}</td>
        <td>{{catalogo.especificacion}}</td>
        <td>{{catalogo.imagen}}</td>
      </tr>
    </tbody>
...

异步管道将自动取消订阅 https://angular.io/api/common/AsyncPipe

【讨论】:

  • 即使这样也会抛出同样的错误
  • 然后看看后端返回什么,以确保数据类型正确,因为当您的服务工作时,后端必须只返回一个目录数组。例如,如果服务器在“数据”属性或其他内容中返回目录,那么您必须使用地图运算符仅返回该数据。还要检查代码中的错误,如*ngFor="catalogo of catalogo"
  • @robertoalvarez 你看到后端数据了吗?如果您向端点发出原始 GET 请求,您会获得预期格式的数据吗?
  • @Osark,我刚刚做了,但它解析不正确,我现在正在修复它。感谢您的输入,我修复后它应该可以工作。虽然当我尝试执行异步时它无法识别该行,但我不知道为什么。
  • @robertoalvarez 如果异步管道未被识别,那么您可能在某些模块中使用它,而您没有导入有角度的 CommonModule。很高兴听到您发现问题。此外,如果您想以某种方式解析数据,您可以使用 rxjs 管道和映射运算符,以便您可以根据需要更改输入流
猜你喜欢
  • 2016-11-08
  • 2021-01-04
  • 1970-01-01
  • 1970-01-01
  • 2021-05-23
  • 2013-01-08
  • 2020-07-23
  • 2021-04-11
相关资源
最近更新 更多