Angular 2-观察火箱数据库的结果



我是新来的,所以要好心:(

角2(1.0.4(角CLINodejs 7.9

我已经尝试制作一项集中服务,以检查用户是否已登录,并且是否进行了检索并将用户的数据发送回...我只是尝试2天以使此方法无效。任何帮助将不胜感激:

    import { Injectable } from '@angular/core';
    import { Component, OnInit } from '@angular/core';
    import { AngularFireAuth } from 'angularfire2/auth';
    import { AngularFireDatabaseModule, AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';
    import { Observable } from 'rxjs/Rx';
    import { TipoUtente } from './tipidati' ;
    import {Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from '@angular/router';
    import * as firebase from 'firebase';
    import 'rxjs/add/operator/toPromise' ;

    @Injectable()
    export class StatoutenteService implements OnInit {
constructor(private db: AngularFireDatabase, private afAuth: AngularFireAuth, private router: Router) {}
public getUserData() : Observable<any> {
  this.afAuth.authState.map( auth => {
        if (auth == null) {
          this.Logged = false ;
          this.Utente = new TipoUtente() ;
          this.UId = '' ;
          return undefined ;
        } else {
          this.Logged = true  ;
          this.UId = auth.uid ;
          return this.dbUserData().then(data => {
              console.log('leggo promessa') ;
              console.log(data) ;
              if (data.Livello != undefined) this.Utente = data ; else this.Utente = undefined ;
              console.log(this.Utente) ;
              if ( this.Utente == undefined ) { this.createNewUser() }
            } ) ;
        }
      } ) ;

} ;
private dbUserData() : Promise<TipoUtente> {
  // Controllo Utente
  console.log('Recupero dati utente!') ;
  console.log('UID :' + this.UId ) ;
  console.log(this.Logged) ;
  let utenteX = this.db.object('users/' + this.UId)
  return new Promise((resolve, reject) => {
    // must import 'rxjs/add/operator/first'; before using it here
    utenteX.subscribe( data  => {
      if ( data.$value == null ) resolve(undefined); else resolve(data) ;
    }, reject);
  });
}

主要问题是您的getuserdata((不会返回任何东西。您需要返回OVServable。

return this.afAuth.authState.map( auth => { ....

然后,您应该能够通过订阅getUserData((之类的访问UserData:

this.statoutenteService.getUserData().subscribe(promisedUserData => {...})

但实际上混合承诺和可观察到的不是一个好习惯。尝试像这样重组:

export class StatoutenteService implements OnInit {
    Logged: boolean;
    UId: string;
    Utente: TipoUtente;
    constructor(private db: AngularFireDatabase, private afAuth: AngularFireAuth, private router: Router) {
         this.Logged = false;
         this.UId = '';
         this.Utente = new TipoUtente();
    }
    public getUserData() : Observable<any> {
      return this.afAuth.authState
         .filter(auth => !!auth)  //filters out events where auth is not truthy
         .flatMap( auth => {      //flatMap will resolve the returned observable (chaining observables)
             this.Logged = true;
             this.UId = auth.uid;
             return this.db.object('users/' + this.UId);
        }).map(data => {
             if (data.Livello != undefined)  
                 this.Utente = data; 
             else 
                 this.Utente = undefined;
             console.log(this.Utente) ;
             if (this.Utente == undefined)  
                 return this.createNewUser();
             return null; 
        });
    }
}

那么您没有承诺的开销。然后,当您订阅可观察到的getuserdata((时,您将获得最后的映射函数返回。因此,现在您将获得this.createnewuser((的返回值;如果这个。否则为null。

您可以通过订阅它来以相同的方式访问它:

this.statoutenteService.getUserData().subscribe(user => {...})

希望对您有帮助。

你好,谢谢你的答案:(我只是为我编辑一些工作,现在结果好多了。然后我以前的代码(谢谢!!(

我只需要在不是auth时收到一个"空"用户的现在...我尝试将您的代码编辑为UP,但我会得到一个充满活力。

所以我尝试制作此模式:

  1. Menubar致电服务要求UserData
  2. 如果用户被记录:梅纳巴尔获取用户数据并根据级别更新按钮
  3. 如果未记录用户:Menubar显示"登录"按钮并隐藏菜单。

到目前为止,这是编辑的代码:

服务:

      public getUserData() : Observable<any> {
        return this.afAuth.authState
           .flatMap( auth => {      //flatMap will resolve the returned observable (chaining observables)
               if ( auth == null ) {
                 this.Logged = false;
                 return undefined ;  // <<< Angular doesn't like this because it expect a stream
               } else {
               this.Logged = true;
               this.UId = auth.uid;
               return this.db.object('users/' + this.UId);
               }
          }).map(data => {
               console.log('sono dentro data') ;
               console.log(data) ;
               if (data.Livello != undefined) {
                   console.log('sono dentro if') ;
                   this.Utente = data;
               } else {
                   this.Utente = undefined; }
               console.log(this.Utente) ;
               if (this.Utente == undefined) return this.createNewUser(); else return data ;
          });
      }
private createNewUser() : Observable<any> {
  // Creo utente
  console.log('Creo Utente!') ;
  console.log(this.Logged) ;
  // se non sono loggato ritorno Livello 0
  if ( !this.Logged ) { return undefined } ;
  // carico dati in Utente :
  this.afAuth.authState.subscribe(auth => {
    if (auth != undefined) {
    console.log('sono in MAP') ;
  this.Utente = new TipoUtente() ;
  this.Utente.Cognome = auth.displayName.split(" ")[0] ;
  this.Utente.Nome    = auth.displayName.split(" ")[1] ;
  this.Utente.DisplayName = auth.displayName ;
  this.Utente.Immagine = auth.photoURL ;
  this.Utente.Livello = 1 ;
  this.UId = auth.uid ;
  // scrivo utente :
  console.log('chiamo DB') ;
  return this.db.database.ref('users/' + auth.uid).set(this.Utente) ;
  }
}) ;

Menubar:

this.StatoUtente.getUserData().subscribe(data => {
    this.Utente = data ;
    console.log(data) ;
    if ( data != undefined ) {
        this.btntext = "Accedi" ;
        this.LevelMenu = 0 ;
        this.router.navigateByUrl('/') ;
      } else {
        this.btntext = "Logout" ;
        this.Utente = data ;
        this.LevelMenu = this.Utente.Livello ;
      }
    })

最新更新