使用Firebase添加管理员后,Angular网站会将所有用户重定向到首页,包括管理员

时间:2018-07-28 15:36:44

标签: angular firebase

我正在从在线教程中练习这个项目。这里有些页面只能由admin访问。一个名为isAdmin的属性设置了admin用户,但是在添加admin之后,我总是被重定向到所有用户的主页包括admin。我还没有向Firebase中的任何其他用户添加isAdmin属性。

app.module.ts:

export const appRoutes: Routes = [

  {path:'',component:HomeComponent},
  {path:'products',component:ProductsComponent},
  {path:'shopping-cart',component:ShoppingCartComponent},
  {path:'login',component:LoginComponent},

  {path:'check-out',component:CheckOutComponent,canActivate:[AuthGuard]},
  {path:'order-sucessful',component:OrderSucessfulComponent,canActivate:[AuthGuard]},
  {path:'my/orders',component:MyOrdersComponent,canActivate:[AuthGuard]},

  {path:'admin/products',component:AdminProductsComponent,canActivate:[AuthGuard,Adminauthguard]},
  {path:'admin/orders',component:AdminOrdersComponent,canActivate:[AuthGuard,Adminauthguard]}

  ]


@NgModule({
  declarations: [
    AppComponent,
    BsNavbarComponent,
    HomeComponent,
    ProductsComponent,
    ShoppingCartComponent,
    CheckOutComponent,
    OrderSucessfulComponent,
    MyOrdersComponent,
    AdminProductsComponent,
    AdminOrdersComponent,
   LoginComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(appRoutes),
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireDatabaseModule,
    AngularFireDatabaseModule,
    NgbModule.forRoot()

  ],

  providers: [AngularFireAuth,AuthService,AuthGuard,Adminauthguard],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.user.ts:

export interface AppUser{
name:string;
email:string;
isAdmin:boolean;
}

user.service.ts:

import { Injectable } from '@angular/core';
import { AngularFireDatabase,FirebaseObjectObservable } from '../../node_modules/angularfire2/database';
import * as firebase from 'firebase';
import { AppUser } from './models/app.user';

@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):FirebaseObjectObservable<AppUser>{
      return this.db.object('/users'+uid)
    }
  }

adminroutegaurdservice.ts:

export class Adminauthguard implements CanActivate {

  constructor(private auth:AuthService,private userService:UserService) { }

  canActivate(): Observable<boolean>{
     return this.auth.user$
     .switchMap(user=>this.userService.get(user.uid))
     .map(appUser=>appUser.isAdmin);
  }

}

0 个答案:

没有答案