我正在尝试在我的角度2应用程序中注入服务,但是当我在角度/路由器中调用canactivate()时,服务未定义。如何在调用canactivate()之前注入服务。 enter image description here
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 {
}
答案 0 :(得分: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 {
}