【问题标题】:with HttpClient i get: Error: Cannot find a differ supporting object '[object Object]' of type 'object' [duplicate]使用 HttpClient 我得到:错误:找不到类型为“对象”的不同支持对象“[对象对象]”[重复]
【发布时间】:2018-10-27 21:00:53
【问题描述】:

我正在尝试通过 json 显示数据,我正在关注本教程 https://www.djamware.com/post/59924f9080aca768e4d2b12e/ionic-3-consuming-rest-api-using-new-angular-43-httpclienthttps://jsonplaceholder.typicode.com/users 它完美地显示了数据,但使用这个 { 名称:“维克多”, 阿佩里多:“罗伯斯”, 赛杜拉:“18617014”, fecha_nacimiento: "23-08-1987", 专业:“ing en informatica” }

我明白了,错误:找不到“object”类型的不同支持对象“[object Object]”。 NgFor 只支持绑定到 Arrays 等 Iterables。

这是我的提供者/rest.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

/*
  Generated class for the RestProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class RestProvider {

  apiUrl = 'http://192.168.0.106:8000/api';

  constructor(public http: HttpClient) {
    console.log('Hello RestProvider Provider');
  }

  getUsers() {
    return new Promise(resolve => {
      this.http.get(this.apiUrl+'/users').subscribe(response => {
        resolve(response);
      }, err => {
        console.log(err);
      });
    });
  }

  addUser(data) {
    return new Promise((resolve, reject) => {
      this.http.post(this.apiUrl+'/users', JSON.stringify(data))
        .subscribe(res => {
          resolve(res);
        }, (err) => {
          reject(err);
        });
    });
  }

}

这是我的 show-posts.ts

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, MenuController } from 'ionic-angular';
import { RestProvider } from '../../providers/rest/rest';


/**
 * Generated class for the ShowPostsPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-show-posts',
  templateUrl: 'show-posts.html',
})
export class ShowPostsPage {
  users: any;
  constructor(public navCtrl: NavController, public navParams: NavParams, public menuCtrl: MenuController,
   public restProvider: RestProvider) {
    // Cerrar menu cuando se ingrese a ClassesPage
    this.menuCtrl.close();  

    this.getUsers();
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad ShowPostsPage');
  }

  getUsers() {
    this.restProvider.getUsers()
    .then(data => {
      this.users = data;
      console.log(this.users);
    });
  }

}

这是我的 show-posts.html

<!--
  Generated template for the ShowPostsPage page.

  See http://ionicframework.com/docs/components/#navigation for more info on
  Ionic pages and navigation.
-->
<ion-header>

  <ion-navbar>
    <ion-title>Usuarios</ion-title>
  </ion-navbar>

</ion-header>


<ion-content padding>
  <ion-list inset>
    <ion-item *ngFor="let user of users">
      <h2>{{user.nombre}}</h2>
      <p>{{user.cedula}}</p>
      <!-- <p>{{Usuarios.cedula}}</p>
      <p>{{Usuarios.fecha_nacimiento}}</p>
      <p>{{Usuarios.profesion}}</p> -->
    </ion-item>
  </ion-list>
</ion-content>

*忽略名称,我知道我正在显示用户,没有帖子,但这只是一个尝试。我对 api 很陌生,一切都很好

我通过控制台日志获取数据

{nombre: "Víctor", Apellido: "Robles", cedula: "18617014", fecha_nacimiento: "23-08-1987", profesion: "ing en informatica"}Apellido: "Robles"cedula: "18617014"fecha_nacimiento: "23-08-1987"nombre: "Víctor"profesion: "ing en informatica"__proto__: Object
ShowPostsPage.html:18 ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
    at NgForOf.ngOnChanges (VM1115 vendor.js:39917)
    at checkAndUpdateDirectiveInline (VM1115 vendor.js:12781)
    at checkAndUpdateNodeInline (VM1115 vendor.js:14309)
    at checkAndUpdateNode (VM1115 vendor.js:14252)
    at debugCheckAndUpdateNode (VM1115 vendor.js:15145)
    at debugCheckDirectivesFn (VM1115 vendor.js:15086)
    at Object.eval [as updateDirectives] (VM1224 ShowPostsPage.ngfactory.js:58)
    at Object.debugUpdateDirectives [as updateDirectives] (VM1115 vendor.js:15071)
    at checkAndUpdateView (VM1115 vendor.js:14218)
    at callViewAction (VM1115 vendor.js:14569)
View_ShowPostsPage_0 @ ShowPostsPage.html:18
proxyClass @ compiler.js:14659
DebugContext_.logError @ core.js:15038
ErrorHandler.handleError @ core.js:1510
IonicErrorHandler.handleError @ ionic-error-handler.js:61
(anonymous) @ core.js:5925
t.invoke @ polyfills.js:3
r.run @ polyfills.js:3
NgZone.runOutsideAngular @ core.js:4708
ApplicationRef.tick @ core.js:5925
(anonymous) @ core.js:5751
t.invoke @ polyfills.js:3
onInvoke @ core.js:4760
t.invoke @ polyfills.js:3
r.run @ polyfills.js:3
NgZone.run @ core.js:4577
next @ core.js:5751
schedulerFn @ core.js:4342
SafeSubscriber.__tryOrUnsub @ Subscriber.js:242
SafeSubscriber.next @ Subscriber.js:189
Subscriber._next @ Subscriber.js:129
Subscriber.next @ Subscriber.js:93
Subject.next @ Subject.js:55
EventEmitter.emit @ core.js:4322
checkStable @ core.js:4725
onHasTask @ core.js:4773
t.hasTask @ polyfills.js:3
t._updateTaskCount @ polyfills.js:3
r._updateTaskCount @ polyfills.js:3
r.runTask @ polyfills.js:3
o @ polyfills.js:3
e.invokeTask @ polyfills.js:3
p @ polyfills.js:2
v @ polyfills.js:2
error (async)
O @ polyfills.js:2
t.scheduleTask @ polyfills.js:3
onScheduleTask @ polyfills.js:3
t.scheduleTask @ polyfills.js:3
r.scheduleTask @ polyfills.js:3
r.scheduleEventTask @ polyfills.js:3
(anonymous) @ polyfills.js:2
(anonymous) @ http.js:2353
Observable._trySubscribe @ Observable.js:172
Observable.subscribe @ Observable.js:160
subscribeToResult @ subscribeToResult.js:23
MergeMapSubscriber._innerSub @ mergeMap.js:132
MergeMapSubscriber._tryNext @ mergeMap.js:129
MergeMapSubscriber._next @ mergeMap.js:112
Subscriber.next @ Subscriber.js:93
ScalarObservable._subscribe @ ScalarObservable.js:49
Observable._trySubscribe @ Observable.js:172
Observable.subscribe @ Observable.js:160
MergeMapOperator.call @ mergeMap.js:87
Observable.subscribe @ Observable.js:157
FilterOperator.call @ filter.js:60
Observable.subscribe @ Observable.js:157
MapOperator.call @ map.js:56
Observable.subscribe @ Observable.js:157
(anonymous) @ rest.ts:23
t @ polyfills.js:3
webpackJsonp.165.RestProvider.getUsers @ rest.ts:22
webpackJsonp.108.ShowPostsPage.getUsers @ show-posts.ts:51
ShowPostsPage @ show-posts.ts:43
createClass @ core.js:12491
createDirectiveInstance @ core.js:12326
createViewNodes @ core.js:13784
createRootView @ core.js:13673
callWithDebugContext @ core.js:15098
debugCreateRootView @ core.js:14381
ComponentFactory_.create @ core.js:11278
ComponentFactoryBoundToModule.create @ core.js:4030
NavControllerBase._viewInit @ nav-controller-base.js:441
(anonymous) @ nav-controller-base.js:254
t.invoke @ polyfills.js:3
onInvoke @ core.js:4760
t.invoke @ polyfills.js:3
r.run @ polyfills.js:3
(anonymous) @ polyfills.js:3
t.invokeTask @ polyfills.js:3
onInvokeTask @ core.js:4751
t.invokeTask @ polyfills.js:3
r.runTask @ polyfills.js:3
o @ polyfills.js:3
e.invokeTask @ polyfills.js:3
p @ polyfills.js:2
v @ polyfills.js:2
ShowPostsPage.html:18 ERROR CONTEXT DebugContext_ {view: {…}, nodeIndex: 20, nodeDef: {…}, elDef: {…}, elView: {…}}

【问题讨论】:

  • 问题是'this.users' 不是一个数组。您必须为 ngFor 提供一个数组(更准确地说,是一个 Iterable)。
  • 你能显示 console.log(data) 吗?长什么样子
  • 是的,我用所有控制台输出编辑了问题,我可以通过控制台看到数据
  • 只是一个建议,您可以通过在 this.http.method() 调用之后附加 .toPromise() 来承诺您的 observable。

标签: json angular api ionic-framework


【解决方案1】:

从您的日志看来,通过的数据似乎只是单个用户 (victor robles)。这是主要问题。 但是,我建议将您的 users 属性声明为 any[] 而不仅仅是 any。然后包装你的单个用户,即data[],如果你想解决它。

this.users = [data];

再一次,您没有从您的服务中获得用户列表。如果它是一个用户列表,而不是单个对象,它应该是一个集合(一个数组)。

【讨论】:

    猜你喜欢
    • 2020-07-07
    • 1970-01-01
    • 2017-04-22
    • 2021-03-17
    • 2018-10-12
    • 2020-11-22
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多