gpt4 book ai didi

javascript - Angular 2 : Unhandled Promise rejection: No provider for AuthService! ;区域: Angular

转载 作者:行者123 更新时间:2023-12-01 03:04:13 26 4
gpt4 key购买 nike

我使用 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 并通过构造函数将其注入(inject)到组件中。我还检查了 AuthService 是否已导入到 AppModule 文件中并添加到提供者数组中,以便它可以用作单例服务。

编辑以添加代码示例:

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

@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
) {}

验证服务:

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({}) 装饰中添加一行内容:

提供者:[AuthService]

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

请参阅此官方 Angular 2 documentation 中的前几段

关于javascript - Angular 2 : Unhandled Promise rejection: No provider for AuthService! ;区域: Angular ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46306378/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com