我在AngularFireObject中使用异步时遇到问题。解决方案是什么?
HomePage.ts:
import { AngularFireObject } from 'angularfire2/database';
export class HomePage {
profileData: AngularFireObject<any>;
constructor(public authProvider: AuthProvider){}
ionViewWillLoad(){
// Here is returning the user logged in correctly
// and passing data.uid as parameter
this.authProvider.authState().subscribe(data => {
this.profileData = this.authProvider.getUserProfile(data.uid);
})
}
HomePage.html:
<ion-content padding>
<p>Nome: {{(profileData | async)?.nome}}</p>
</ion-content>
AuthProvider.ts:
export class AuthProvider {
constructor(
private afAuth: AngularFireAuth,
private afDatabase: AngularFireDatabase) {}
getUserProfile(data: any) {
return this.afDatabase.object(`user-profile/${data.uid}`); // returns AngularFireObject
}
当我尝试在AngularFireObject上使用异步时,会返回以下错误。
Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'
at invalidPipeArgumentError (http://localhost:8100/build/vendor.js:22387:12)
at AsyncPipe._selectStrategy (http://localhost:8100/build/vendor.js:23798:15)
at AsyncPipe._subscribe (http://localhost:8100/build/vendor.js:23780:31)
at AsyncPipe.transform (http://localhost:8100/build/vendor.js:23754:22)
at Object.eval [as updateRenderer] (ng:///AppModule/HomePage.ngfactory.js:132:73)
at Object.debugUpdateRenderer [as updateRenderer] (http://localhost:8100/build/vendor.js:14730:21)
at checkAndUpdateView (http://localhost:8100/build/vendor.js:13866:14)
at callViewAction (http://localhost:8100/build/vendor.js:14211:21)
at execComponentViewsAction (http://localhost:8100/build/vendor.js:14143:13)
at checkAndUpdateView (http://localhost:8100/build/vendor.js:13867:5)
答案 0 :(得分:0)
您的this.profileData
技术上不是Observable
,直到this.authProvider.authState()
已解决。这就是async
管道抛出错误的原因,因为它从一开始就期待Observable
。
您可以做的是,您可以使用.switchMap
转换Observable,如下所示:
this.profileData = this.authProvider.authState().switchMap(data => {
return this.authProvider.getUserProfile(data.uid);
})
答案 1 :(得分:0)
valueChanges()方法返回 Observable ,错误不会发生,但不会显示任何值。
记录保存正确,我不明白为什么它不显示值。
<强> AuthProvider.ts:强>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.9/d3.min.js"></script>
<强> HomePage.ts:强>
{
"message": "Uncaught TypeError: d3.tree is not a function",
"filename": "https://stacksnippets.net/js",
"lineno": 43,
"colno": 22
}
答案 2 :(得分:0)
试试这个
HomePage.ts
import { AngularFireObject } from 'angularfire2/database';
export class HomePage {
profileData: AngularFireObject<any>;
item: any = {};
constructor(public authProvider: AuthProvider){}
ionViewWillLoad() {
this.authProvider.authState().subscribe(data => {
this.itemRef = this.afDatabase.object(`user-profile/${data.uid}`);
this.itemRef.valueChanges()
.subscribe(item => {
this.profileData = item;
});
})
}
HomePage.html
<ion-content padding>
<p>Nome: {{ profileData?.nome }}</p>
</ion-content>