You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ionic 3报错:尝试对比'[object Object]',FCM通知循环展示失败

解决Ionic 3中FCM推送循环展示的报错问题

嘿,刚上手Ionic 3和TypeScript碰到这个问题太正常啦,我来帮你拆解一下~

先搞懂报错原因

你看到的 HomePage.html:18 ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed 这个错误,核心原因很简单:你在模板里用 *ngFor 循环的不是数组(或可迭代集合),而是一个单独的对象。Angular的 *ngFor 只能遍历数组这类可迭代的内容,没法直接遍历单个对象,所以才会抛出这个“diff”相关的错误。

一步步排查修改

结合你提到的几个文件,咱们按顺序来调整:

1. 先检查HomePage的变量定义(home.ts)

首先要确保你用来存储推送通知的变量是数组类型,并且初始化为空数组,避免它变成单个对象:

import { Component } from '@angular/core';
import { NavParams } from 'ionic-angular';
// 如果有定义推送的接口,也可以引入
// import { Notification } from '../data';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  // 声明为数组类型,初始化为空数组
  notifications: any[] = []; // 或者用具体接口:Notification[] = [];

  constructor(public navParams: NavParams) {}

  ionViewDidLoad() {
    // 从导航参数里接收FCM推送的数据
    const newNotification = this.navParams.get('notification');
    if (newNotification) {
      // 重点:把单个推送对象添加到数组里,而不是直接赋值覆盖
      this.notifications.push(newNotification);
    }
  }
}

2. 调整FCM推送的传递逻辑(app.component.ts)

确保你在接收FCM推送后,是把单个推送对象传给HomePage,而不是传一个非数组的结构:

import { HomePage } from '../pages/home/home';
import { FCM } from '@ionic-native/fcm';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage: any = HomePage;

  constructor(private fcm: FCM, private navCtrl: NavController) {
    this.fcm.onNotification().subscribe(data => {
      if (data.wasTapped) {
        // 应用在后台时点击推送打开
        this.navCtrl.push(HomePage, { notification: data });
      } else {
        // 应用在前台时收到推送,直接添加到HomePage的数组里
        // 如果HomePage已经是当前页面,可以通过获取实例来添加
        const activeNav = this.navCtrl.getActive();
        if (activeNav && activeNav.instance instanceof HomePage) {
          (activeNav.instance as HomePage).notifications.push(data);
        }
      }
    });
  }
}

3. 确认data.ts的结构(如果有定义接口)

如果你的data.ts是用来定义推送数据的结构,要确保是单个推送的接口,而不是数组:

// data.ts
export interface Notification {
  title: string;
  body: string;
  // 其他你需要的字段,比如推送时间、图标等
}

然后在home.ts里用这个接口来约束数组类型,代码更规范。

4. 修正HomePage模板的循环(home.html)

确保你的*ngFor是遍历数组变量,比如第18行的循环应该是这样:

<!-- home.html -->
<ion-content padding>
  <h3>推送通知</h3>
  <!-- 遍历notifications数组,每个元素是单个推送对象 -->
  <ion-list>
    <ion-item *ngFor="let notify of notifications" key="{{notify.title}}">
      <h2>{{notify.title}}</h2>
      <p>{{notify.body}}</p>
    </ion-item>
  </ion-list>
</ion-content>

注意:如果数组里的元素没有唯一标识,可以加个key属性帮助Angular优化渲染,避免重复问题。

最后再检查几个关键点

  • 永远不要让notifications变量变成单个对象,哪怕初始状态也要是空数组[],不能是{}或者undefined。
  • 如果是从后端接口获取历史推送,要确认接口返回的是数组格式,而不是单个对象。如果返回单个对象,要把它放进数组再赋值给notifications。

内容的提问来源于stack exchange,提问作者Zubli Quzaini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:22:05