我正在尝试在我的 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 {
}