【问题标题】:ERROR Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'ERROR 错误:InvalidPipeArgument:管道“AsyncPipe”的“[object Object]”
【发布时间】:2018-06-22 08:28:50
【问题描述】:

我在尝试从 firebase 获取用户个人资料数据并将其显示在主页上时遇到异步错误。我尝试删除 home.html 中的异步,这消除了错误,但没有显示数据。

InvalidPipeArgument: '[object Object]' 用于管道'AsyncPipe'

home.ts

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ToastController } from 'ionic-angular';
import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFireDatabase, FirebaseObjectObservable } from 'angularfire2/database';
import { Profile } from './../../models/profile';


@IonicPage()
@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
})
export class HomePage {

  profileData: FirebaseObjectObservable<Profile>

  constructor(private afAuth: AngularFireAuth, private afDatabase: AngularFireDatabase,
    private toast: ToastController, public navCtrl: NavController, public navParams: NavParams) {
  }

  ionViewWillLoad() {
    this.afAuth.authState.take(1).subscribe(data => {
      if (data && data.email && data.uid) {
        this.profileData = this.afDatabase.object(`profile/${data.uid}`)
      }
      else {
        this.navCtrl.setRoot('LoginPage');
      }
    })
  }
}

home.html

<ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <p>Username: {{(profileData | async)?.username}} </p>
  <p>Date of Birth: {{(profileData | async)?.birthdate}} </p>
</ion-content>

【问题讨论】:

标签: angular typescript firebase ionic-framework ionic3


【解决方案1】:

FirebaseObjectObservable&lt;Profile&gt; 不是async 管道将识别的类型。

这是AsyncPipe的源代码链接:https://github.com/angular/angular/blob/5.2.0/packages/common/src/pipes/async_pipe.ts#L43-L145

注意第 119 行以下函数:

private _selectStrategy(obj:Observable<any>|Promise<any>|EventEmitter<any>): any {
    if (ɵisPromise(obj)) {
      return _promiseStrategy;
    }

    if (ɵisObservable(obj)) {
      return _observableStrategy;
    }

    throw invalidPipeArgumentError(AsyncPipe, obj);
  }

由于profileData 不是PromiseObservable,它正在抛出invalidPipeArgumentError。您需要将数据转换为标准的 Observable 或 Promise 才能使用 async 管道。

您可以使用.valueChanges() 方法(返回Observable)并将profileData 的类型更改为Observable

【讨论】:

【解决方案2】:
this.profileData = this.afDatabase.object(`profile/${data.uid}`).valueChanges();

您必须添加 .vauleChanges() 这应该可以清除错误并显示数据。

【讨论】:

    猜你喜欢
    • 2018-05-23
    • 1970-01-01
    • 2018-05-11
    • 2021-01-02
    • 1970-01-01
    • 2017-12-05
    • 2018-03-18
    • 1970-01-01
    相关资源
    最近更新 更多