我刚开始使用 Angular,在使用 JwtHelperService 时遇到此错误:
“错误 NullInjectorError:R3InjectorError(独立 [_LoginComponent])[_AuthService -> _AuthService -> _AuthService -> JwtHelperService -> JwtHelperService]: NullInjectorError:没有 JwtHelperService 的提供者!” 也许是因为我的组件是独立的。
我创建了一个身份验证服务来处理从后端收到的令牌:
import { Injectable } from '@angular/core';
import { JwtHelperService } from '@auth0/angular-jwt';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private jwtHelper: JwtHelperService) { }
getToken(): string | null {
return localStorage.getItem('access_token');
}
decodeToken(): any {
const token = localStorage.getItem('access_token');
const decode = token ? this.jwtHelper.decodeToken(token) : null;
console.log(decode);
return token ? this.jwtHelper.decodeToken(token) : null;
}
isLoggedIn(): boolean {
const token = localStorage.getItem('access_token');
return !this.jwtHelper.isTokenExpired(token);
}
logout(): void {
localStorage.removeItem('access_token');
}
getSessionInfo(): { Name: string, NameIdentifier: string } |null {
const decodedToken = this.decodeToken();
if (decodedToken && decodedToken.unique_name && decodedToken.nameid) {
return { Name: decodedToken.unique_name, NameIdentifier: decodedToken.nameid };
}
return null;
}
}
我也尝试将其导入到loginComponent中:
import { JwtHelperService } from '@auth0/angular-jwt';
import { AuthService } from '../services/auth.service';
@Component({
selector: 'app-login',
standalone: true,
imports: [ReactiveFormsModule, CommonModule],
template: `
...
`,
styleUrl: './login.component.css',
providers: [JwtHelperService]
})
export class LoginComponent {
loginForm = new FormGroup({
email : new FormControl('', Validators.required),
password : new FormControl('', Validators.required),
});
submitted = false;
loading = false;
errorMessage: string ='';
sessionInfo: { Name: string, NameIdentifier: string } = { Name: '', NameIdentifier: '' };
constructor(private userService: UserService, private router: Router, private authService: AuthService){}
submitLogin(){
console.log("click");
this.submitted = true;
this.loading = true;
const userLogin = new UserLogin();
userLogin.email = this.loginForm.value.email ?? '';
userLogin.password = this.loginForm.value.password ?? '';
this.userService.submitLogin(userLogin).pipe(first()).subscribe(success => {
if (success) {
const session = this.authService.getSessionInfo();
if(session){
this.sessionInfo = session;
this.router.navigate(['/']);
}
else {
console.log("Session is null");
}
} else {
this.loading = false;
this.errorMessage = "Email or password incorrect"
}
});
}
}
但我仍然遇到同样的错误。
我还将它导入到app.config中:
import { JwtModule, JwtHelperService } from '@auth0/angular-jwt';
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes), provideHttpClient(withInterceptors([userInterceptor])),
importProvidersFrom(
HttpClientModule,
JwtModule.forRoot({
config: {
}
})
),
JwtHelperService
]
};
如果您发现我的代码有任何不一致之处,请告诉我
文档:angular2-jwt
import { JwtModule } from "@auth0/angular-jwt";
import { provideHttpClient, withInterceptorsFromDi } from "@angular/common/http";
export function tokenGetter() {
return localStorage.getItem("access_token");
}
bootstrapApplication(AppComponent, {
providers: [
// ...
importProvidersFrom(
JwtModule.forRoot({
config: {
tokenGetter: tokenGetter,
allowedDomains: ["example.com"],
disallowedRoutes: ["http://example.com/examplebadroute/"],
},
}),
),
provideHttpClient(
withInterceptorsFromDi()
),
],
});