我使用AuthService和AuthGuard登录/注销用户并保护路由。在AuthGuard和LoginComponent中使用AuthService。 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文件并添加到provider数组,以便可以将其用作单例服务。

编辑以添加代码示例:

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

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

    ...
}

最佳答案

在您的app.component类@Component({})装饰中添加一行,指出:

providers: [AuthService]

这将在该级别为该服务创建单例服务。如果要提供更详细的级别,则可以在较低的级别提供(实例化)它。

请参阅此官方角度2 documentation的前几段

关于javascript - Angular 2:未处理的 promise 拒绝:没有AuthService提供程序! ;区域: Angular ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46306378/

10-10 12:41