angularfire icon indicating copy to clipboard operation
angularfire copied to clipboard

Just get the value once with no subscription

Open bradintheusa opened this issue 10 years ago • 31 comments

Hi

I want just a snapshot of a node and not subscribe to updates. What is the best way to do this? I tried

var team = this.af.database.object('/teams/' , { preserveSnapshot: true }).first();
team.subscribe(snapshot => {
     // code here....
}

But i get a compile error on the call to first{}

store.ts (187, 92): Property 'first' does not exist on type 'FirebaseObjectObservable<any>'.

What is the best way to no receive updates.

Thanks Brad

bradintheusa avatar Aug 20 '16 03:08 bradintheusa

Similar question: #380

ray-z avatar Aug 22 '16 13:08 ray-z

Use .take(1), which will kill the subscription once the first value has emitted.

var team = this.af.database.object('/teams/' , { preserveSnapshot: true }).take(1);

davideast avatar Aug 22 '16 18:08 davideast

Thanks.

bradintheusa avatar Aug 22 '16 23:08 bradintheusa

do you have any idea about this error: Property 'take' does not exist on type 'FirebaseListObservable<any[]>'.? It used to work.

andreigiura avatar Sep 17 '16 06:09 andreigiura

same here, Property 'take' does not exist on type 'FirebaseListObservable'

danielordonez avatar Sep 22 '16 03:09 danielordonez

i figured it out. you should do this: import 'rxjs/add/operator/take'

andreigiura avatar Sep 22 '16 05:09 andreigiura

and maybe also this: import {Observable} from 'rxjs/Rx';

andreigiura avatar Sep 22 '16 05:09 andreigiura

Thank you @andreigiura , I was able to use the .take property.

danielordonez avatar Sep 22 '16 15:09 danielordonez

Hey guys, is it possible to use take in this case?


this.af.database.object('/users/'+this.uid).take(1).update({
              provider: auth.facebook.providerId,
                name: auth.facebook.displayName,
                email: auth.facebook.email,
          });

Whenever the user is logging in, I run this to save his data in my users node. Unlucky, whenever the user logs out I get this error:

FIREBASE WARNING: Exception was thrown by user callback. Error: permission_denied at /users/userID: Client doesn't have permission to access the desired data.
    at Error (native)
    at G (http://localhost:4200/main.bundle.js:75367:36)
    at Object.G (http://localhost:4200/main.bundle.js:75371:86)
    at yh (http://localhost:4200/main.bundle.js:75356:98)
    at nh.h.wd (http://localhost:4200/main.bundle.js:75349:310)
    at af.wd (http://localhost:4200/main.bundle.js:75252:364)
    at vd.hg (http://localhost:4200/main.bundle.js:75250:280)
    at yd (http://localhost:4200/main.bundle.js:75203:464)
    at WebSocket.La.onmessage (http://localhost:4200/main.bundle.js:75202:245)
    at WebSocket.wrapFn [as _onmessage] (http://localhost:4200/main.bundle.js:94097:29) 

which means Firebase keep listening to my user until the page is redirected. so I need try run it only once. any ideas?

theunreal avatar Oct 18 '16 09:10 theunreal

I dont think you can use take on an update. The update will be made only once by default. You can only use take with subscribe.

andreigiura avatar Oct 18 '16 09:10 andreigiura

It seems that it's a permission error. You might have some rule on firebase which allows user to read/write data if it's logged in. Do you try to do any operation after the user logged out?

andreigiura avatar Oct 18 '16 09:10 andreigiura

Thanks for the reply @andreigiura. In the user panel, I have this code:

ngOnInit() {
        this.authService.loadUser().subscribe(() => {
            this.user = this.authService.userData;
        });
  }

Which refers to my loadUser() method to get the data from firebase (I just tried to place take(1) but I still get this permission error):

loadUser() {
      return this.af.database.object('/users/'+this.uid).take(1).map(user => {
            this.userData = user;
        });
  }

In my logout I simply do this:

logout() {
      this.auth.logout();
      this.userData = null;
    this.isLoggedIn = false;
    this.router.navigate(['']);
  }

I think the error occurs because firebase is keeping the connection to my user even after this.auth.logout(); and until the router is navigating, he keeps trying to refresh the data. That's why I need to perform this action only once.

theunreal avatar Oct 18 '16 09:10 theunreal

II have a similar setup, i will just show you how i implemented the same functionality. You code looks strange with the mapping on the load user function and then subscribing on the nginit

andreigiura avatar Oct 18 '16 10:10 andreigiura

I'll be happy to check it out. I've been working for days to understand how to structure the angular 2 app to work good with the Firebase authentication. I need to simply save the user data into my database and load it once he logins. that's what it does now, but it's does't feels like it is the best way to do this.

theunreal avatar Oct 18 '16 10:10 theunreal

this is how my authService.ts looks like:

import { Injectable } from '@angular/core'; import { Http, Response, RequestOptions, Headers } from '@angular/http'; import { Router} from '@angular/router'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/take'; import { Events} from './Events';

import { AngularFire, AuthProviders, AuthMethods, FIREBASE_PROVIDERS, FirebaseAuthState } from 'angularfire2';

@Injectable() export class AuthService { public isLoggedIn;

public usersCollection; public userData = null;

constructor (public http : Http, private router: Router, private eventEmitter : Events, public af: AngularFire) { this.isLoggedIn = false;

//subscribe to the auth state
this.af.auth.subscribe(auth => {
  //if the result is not null, setup the public user data which can be accesed through this service
  if(auth != null) {

    this.userData = auth;
    this.isLoggedIn = true;

    //set a route in the users table for this particular user
    this.usersCollection = af.database.object("users/" + this.userData.uid);

    //current date to be saved in the users details, this will be used for the registered at field
    var today = new Date().toLocaleDateString('en-GB', {
        day : 'numeric',
        month : 'short',
        year : 'numeric'
    }).split(' ').join(' ');

    //other data that i need to set in the users table
    var dataToSet = {
      timestamp : Math.floor((new Date()).getTime() / 1000),
      displayName : this.userData.auth.providerData[0].displayName,
      email : this.userData.auth.providerData[0].email,
      photoURL : this.userData.auth.providerData[0].photoURL,
      providerId : this.userData.auth.providerData[0].providerId,
      registeredAt : ""
    };

    //try to get the user from db
    af.database.object("users/" + this.userData.uid).take(1).subscribe((_data) => {
        //if the user does not exist, add the registered at field that we composed else use the entry from the db
          if(!_data.registeredAt) {
            dataToSet.registeredAt = today;
          }else{
            dataToSet.registeredAt = _data.registeredAt;
          }

          //make a hard update to the object (this means that all the data on this firebase route will be replaced and not updated)
          this.usersCollection.set(dataToSet).then((_data) => {
              }).catch((_error) => {
                  console.log(_error)
              })


        })
  }else{

    //set the user details to null
    this.userData = null;
    this.isLoggedIn = false;
  }
});

}

//login with email, password login(username, password) { var self = this; this.af.auth.login({ email : username, password : password }, { provider: AuthProviders.Password, method: AuthMethods.Password }) .catch(function(err) { self.eventEmitter.loginErrorsF(err); }) }

//login with facebook loginWithFacebook () { this.af.auth.login({provider: AuthProviders.Facebook, method: AuthMethods.Popup, scope: ['email']}) }

//login with google loginWithGoogle () { this.af.auth.login({provider: AuthProviders.Google, method: AuthMethods.Popup, scope: ['email'] }) }

//signup with email and pwd signup(username, password) { var self = this; this.af.auth.createUser({ email : username, password : password }) .catch(function(err) { self.eventEmitter.loginErrorsF(err); }) }

//check login is used by auth guard in order to secure the routes checkLogin() { return this.af.auth .take(1) .map((authState: FirebaseAuthState) => !!authState) .do(authenticated => { if (!authenticated) this.router.navigate(['/login']); }); }

logout() { this.af.auth.logout() } }

export const AUTH_SERVICE_PROVIDER = [ AuthService ];

andreigiura avatar Oct 18 '16 10:10 andreigiura

This is the authGuard.ts which uses authservice checklogin function in order to secure routes:

import { Injectable } from '@angular/core'; import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; import { AuthService } from './AuthService';

@Injectable() export class AuthGuard implements CanActivate { constructor(private authService: AuthService, private router: Router) {}

canActivate( // Not using but worth knowing about next: ActivatedRouteSnapshot, state: RouterStateSnapshot ) { return this.authService.checkLogin(); } }

export const AUTH_GUARD_PROVIDERS = [ AuthGuard ];

andreigiura avatar Oct 18 '16 10:10 andreigiura

this is the router which uses the authguard for the secured routes (this will not allow access):

import { HomeComponent } from '../components/home/HomeComponent';

import { AuthGuard } from './Auth/AuthGuard';

import { Routes, RouterModule } from '@angular/router';

export const SunmoolAppRoutes = [ { path: 'home/:category', component: HomeComponent, canActivate : [AuthGuard]}, { path: 'login', component: LoginComponent}, { path: '', redirectTo: 'login', pathMatch: 'full' } ]

export const routing = RouterModule.forRoot(SunmoolAppRoutes);

andreigiura avatar Oct 18 '16 10:10 andreigiura

Hey @andreigiura, few questions:

  1. How do you redirect the user to user panel route after the authorization check? I mean, you don't want to show the main app login page whenever someone access your application.
  2. When you log out from your app, don't you get error_handler.js:47 EXCEPTION: permission_denied at /users/userID: Client doesn't have permission to access the desired data. ? I cloned your service and guard, and in my user panel I get this error and the user is not redirection back to login/app page.

theunreal avatar Oct 18 '16 10:10 theunreal

Hey, i have set up a simple example on github, the repo is here: https://github.com/andreigiura/simple-angular2-firebase-auth

You will need to add your firebase credentials in: src/app/app.module.ts

This works with the latest angular-cli, so make sure you npm install -g angular-cli

andreigiura avatar Oct 18 '16 11:10 andreigiura

as you will see there, in the login component you will listen for the auth state, if it will change from the null state, you will redirect the user to the homepage

andreigiura avatar Oct 18 '16 11:10 andreigiura