我使用AuthService和AuthGuard登录/注销用户和保护路由。 AuthService用于AuthGuard以及LoginComponent。 AuthGuard用于通过CanActivate保护路由。当我尝试运行应用程序时,我收到以下错误:
zone.js:522 Unhandled Promise rejection: No provider for AuthService! ; Zone: angular ; Task: Promise.then ; Value: NoProviderError {__zone_symbol__error: Error: DI Error
at NoProviderError.ZoneAwareError
我已经检查过LoginComponent和AuthGuard都导入AuthService并通过构造函数将其注入组件。我还检查过AuthService是否已导入到AppModule文件中并添加到providers数组中,因此它可以用作单例服务。
已修改为添加代码示例:
我的应用模块包含以下内容:
@NgModule({
imports: [...],
providers: [..., AuthService, AuthGuard, ...],
declarations: [..., LoginComponent, EntryComponent ...],
bootstrap: [EntryComponent]
})
export class AppModule {
}
AuthGuard:
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { ApiConfig } from '../Api';
import { AuthService } from './authservice';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private authService: AuthService,
private router: Router,
private config: ApiConfig
) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
console.log(this.isAuthenticated());
if (this.isAuthenticated()) {
if (this.config.defined) {
return true;
} else {
this.authService.setConfig();
return true;
}
} else {
this.router.navigate(['/Login']);
return false;
}
}
// Checks if user is logged in
isAuthenticated() {
return this.authService.userLoggedIn();
}
}
LoginComponent构造函数:
constructor(
private router: Router,
private notifications: Notifications,
private authService: AuthService
) {}
AuthService:
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { ApiConfig } from '../Api';
@Injectable()
export class AuthService {
constructor(
private http: Http,
private router: Router,
private config: ApiConfig
) {
this.apiRoot = localStorage.getItem('apiRoot');
}
...
}
答案 0 :(得分:1)
在app.component类@Component({})中,添加一行说明:
providers: [AuthService]
这将在该级别为该服务创建单件服务。如果您想以更细粒度的级别提供它,您可以在较低级别提供(实例化)它。
请参阅此官方角度documentation
中的前几段答案 1 :(得分:1)
原来我没有在AuthGuard中正确地大写我的AuthService导入.....
import { AuthService } from './authservice';
应该是
import { AuthService } from './AuthService';
自我注意:导入区分大小写