10

Declared in service like this:

public currentDBUserBS$: any;

constructor(private afDb: AngularFireDatabase){}

fetchUser(uid){
  this.afDb.object(`users/${uid}`).valueChanges().subscribe((dUser) => {
    if (dUser) {
      this.currentDBUserBS$ = dUser;
    }
  });
}

Now trying to use in template

template: `<li *ngIf="(authService.currentDBUserBS$ | async)?.role=='admin'"> Something </li>`

The error stack:

ERROR Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'
    at invalidPipeArgumentError (common.js:4219)
    at AsyncPipe._selectStrategy (common.js:5630)
    at AsyncPipe._subscribe (common.js:5612)
    at AsyncPipe.transform (common.js:5586)
    at Object.View_AppNavigatorComponent_0._co [as updateDirectives] (AppNavigatorComponent.html:40)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:14339)
    at checkAndUpdateView (core.js:13508)
    at callViewAction (core.js:13858)
    at execComponentViewsAction (core.js:13790)
    at checkAndUpdateView (core.js:13514)
ishandutta2007
  • 16,676
  • 16
  • 93
  • 129

3 Answers3

24

You are giving currentDBUserBS$ the object you are fetching from Firebase and not the Observable. If you want to do it this way, you have to remove the | async in your template.

However, you could do the following :

fetchUser(uid){
  this.currentDBUserBS$ = this.afDb.object(`users/${uid}`).valueChanges();
}

.valueChanges() gives you an observable and will update automatically when a new value is emitted or an existing value is modified.

tom
  • 745
  • 5
  • 20
  • ok got it, but is there any difference between the two approaches ? In both cases I would get asynchronus update to my template from db right ? – ishandutta2007 Nov 28 '17 at 10:42
  • @ishandutta2007 the results will almost be the same. The `| async` is used to subscribe to your Observable / BehaviorSubject / Subject in your template. When a new value is emitted, Angular will be notified of the changes. With a `.subscribe`, it will be checked every change detection cycle. – tom Nov 28 '17 at 10:46
4

You must add .valueChanges(); after subscribing operation. It is required as shown below:

 this.courses$=db.list('/courses').valueChanges();
pzaenger
  • 11,381
  • 3
  • 45
  • 46
amr hamdy
  • 41
  • 3
2

You're trying to pass array to async pipe instead of Observable. Just remove the async pipe or assign observable to currentDBUserBS$.

Mateusz Witkowski
  • 1,646
  • 10
  • 24