Working with AngularFireObject and switchMap

后端 未结 3 1774
后悔当初
后悔当初 2021-02-09 06:32

I really don\'t know how to fix this. How can I fix this error?

in user.service.ts:
import { Injectable } from \'@angular/core\';

import { AngularFireDatabase,          


        
3条回答
  •  南笙
    南笙 (楼主)
    2021-02-09 06:48

    Do it this way for Angular 6:

    user.service.ts:
    
    import { Injectable } from '@angular/core';
    
    import { AngularFireDatabase, AngularFireObject } from 'angularfire2/database';
    
    import {AppUser} from './models/app.user';
    import * as firebase from 'firebase';
    import { Observable } from 'rxjs';
    
    @Injectable({
      providedIn: 'root'
    })
    export class UserService {
    
    
      constructor(private db: AngularFireDatabase) { }
    
      save(user: firebase.User) {
        this.db.object('/users/' + user.uid).update({
          name: user.displayName,
          email: user.email
        });
      }
    
      get(uid: string): AngularFireObject {
          return this.db.object('/users/' + uid);
      }
    
    }
    
    
    
    In admin-auth-guard.service.ts:
    
    
    import { UserService } from './user.service';
    import { map, switchMap } from 'rxjs/operators';
    import { AuthService } from './auth.service';
    import { Injectable } from '@angular/core';
    import { CanActivate } from '@angular/router';
    import { Observable } from 'rxjs';
    
    @Injectable({
      providedIn: 'root'
    })
    export class AdminAuthGuard implements CanActivate {
    
      constructor(private auth: AuthService, private userService: UserService) { }
    
      canActivate(): Observable {
        return this.auth.user$
        .pipe(switchMap(user => this.userService.get(user.uid).valueChanges()))
        .pipe(map(appUser => appUser.isAdmin));
       }
    
    }
    

提交回复
热议问题