0

我正在尝试在我的 angular 2 应用程序中注入服务,但是当我在 angular/router 中调用 canactivate() 时,该服务未定义。如何在调用 canactivate() 之前注入服务。 在此处输入图像描述

app.routing.ts

const appRoutes: Routes = [
    {
        path: '',
        component: HomeComponent,
        canActivate: ['AuthGuardService']
    },
    {
        path: 'login',
        component: LoginComponent,
        outlet: 'popup'
    },
    // otherwise redirect to home
    {path: '**', redirectTo: ''}
];

export const appRoutingProviders: any[] = [
    {provide: "AuthGuardService", useValue: AuthGuardService}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

auth.guard.service.ts

import {Injectable, Inject} from '@angular/core';
import {AuthService} from "./auth.service";
import {Router, CanActivate} from "@angular/router";
import {Observable} from "rxjs";

@Injectable()
export class AuthGuardService  implements CanActivate {

  constructor(@Inject(AuthService) private auth, @Inject(Router)  private router) { 
  }
  canActivate() : Observable<boolean> | boolean{


    if(this.auth.loggedIn()) {

      return true;
    }
    this.router.navigate([{outlets: {popup: 'login'}}]);
    return false;
  }
}

app.module.ts

@NgModule({
    declarations: [],
    imports: [ routing    ]
    providers: [
        appRoutingProviders,
        ...AUTH_PROVIDERS,
        AuthService,
        AuthGuardService,
        HttpService,
        {
            provide: AuthHttp,
            useFactory: AuthHttpServiceFactory,
            deps: [Http, RequestOptions]
        },
        IndicesEffectsService,
        DialogServiceService
    ],
    bootstrap: [AppComponent]
})
export class AppModule {
}
4

1 回答 1

0

您需要公开您的路线作为module 尝试:

const appRoutes: Routes =
[
    {
        path: '',
        component: HomeComponent,
        canActivate: [AuthGuardService] // <- no quotes
    },
    {
        path: 'login',
        component: LoginComponent,
        outlet: 'popup'
    },
    // otherwise redirect to home
    {path: '**', redirectTo: ''}
];
@NgModule
({
  imports:   [ RouterModule.forRoot(appRoutes)],
  exports:   [ RouterModule],
  providers: [ AuthGuardService ] // <- provide guard
})
export class AppRoutingModule {}

然后在你的AppModule

@NgModule({
    declarations: [],
    imports: [ AppRoutingModule ] // <- import module here
    providers: [
        appRoutingProviders,
        ...AUTH_PROVIDERS,
        AuthService,
        // AuthGuardService, // <- no need for this
        HttpService,
        {
            provide: AuthHttp,
            useFactory: AuthHttpServiceFactory,
            deps: [Http, RequestOptions]
        },
        IndicesEffectsService,
        DialogServiceService
    ],
    bootstrap: [AppComponent]
})
export class AppModule {
}
于 2017-04-27T16:23:19.860 回答