首页 文章

Angular 2:未处理的Promise拒绝:没有AuthService的提供者! ;区域:棱角分明

提问于
浏览
0

我使用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数组中,因此可以将其用作单例服务 .

Edited to add code samples:

我的应用模块包含以下内容:

@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');
    }

    ...
}

2 回答

  • 1

    在你的app.component类@Component({})中,添加一行说明:

    providers: [AuthService]

    这将在该级别为该服务创建单一服务 . 如果您想以更精细的级别提供它,您可以在较低级别提供(实例化)它 .

    请看这个官方角度的前几段documentation

  • 1

    原来我没有在AuthGuard中正确地大写我的AuthService导入.....

    import { AuthService } from './authservice';
    

    本来应该

    import { AuthService } from './AuthService';
    

    自我注意:导入区分大小写

相关问题