]") : in NgModule AppModule in ./AppModule@-1:-1-6ren"> ]") : in NgModule AppModule in ./AppModule@-1:-1-我已经实现了一个拦截器来添加我可以制作 seucred api 的授权 header 。当我在任何应用程序模块中注入(inject)此服务时出现错误//"无法实例化循环依赖!HttpClient ("-6ren">
gpt4 book ai didi

angular - 无法实例化循环依赖! HttpClient ("[ERROR ->]") : in NgModule AppModule in ./AppModule@-1:-1

转载 作者:行者123 更新时间:2023-12-04 02:00:45 26 4
gpt4 key购买 nike

我已经实现了一个拦截器来添加我可以制作 seucred api 的授权 header 。当我在任何应用程序模块中注入(inject)此服务时出现错误//"无法实例化循环依赖!HttpClient ("[ERROR ->]"): in NgModule AppModule in ./AppModule@-1:-1"

//auth拦截器添加授权bearer

import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { Auth } from './auth.service';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(public auth: Auth) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${this.auth.getToken()}`
}
});
return next.handle(request);
}
}


// Auth service

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';

@Injectable()
export class Auth {
// Store profile object in auth class
userProfile: Object;
public token: string;
constructor(private router: Router, private http: HttpClient) {
// set token if saved in local storage
const currentUser = JSON.parse(localStorage.getItem('currentUser'));
this.token = currentUser;
}
login(username: string, password: string) {
const headers = new HttpHeaders()
.set('Content-Type', 'application/x-www-form-urlencoded')
.set('Accept', 'application/json');
const params = new HttpParams().set('username', username).set('password', password)
.set('grant_type', 'password');
return this.http.post('http://rrrrr/token', params.toString(),
{ headers }).subscribe(data => {
this.token = data['access_token'];
console.log(this.token);
},
err => {
console.log('Error occured');
});
}
getToken() {
return this.token;
}
logout(): void {
// clear token remove user from local storage to log user out
this.token = null;
localStorage.removeItem('currentUser');
}
public authenticated(): boolean {
// Check whether the current time is past the
// access token's expiry time
const expiresAt = JSON.parse(localStorage.getItem('expires_at'));
return new Date().getTime() < expiresAt;
}
}

最佳答案

您的 Auth 服务依赖于 HttpClient,这会导致循环依赖。

您可以将 Auth 服务分成两部分:一个具有大部分现有功能的 Auth 和一个具有您的 getToken() 函数(也许还有其他函数)。然后,您的 Auth 服务可以依赖于您的 AuthContextService,您的 AuthInterceptor 也是如此。

编辑:添加一些代码来尝试解释

@Injectable()
export class AuthContextService {
// With getToken() in here, and not in Auth, you can use it in AuthInterceptor
getToken(): string {
return 'however you get your token';
}
}

@Injectable()
export class Auth {
constructor (private http: HttpClient, private authContext: AuthContextService) {}

authenticate(username: string, password: string) {
// Do stuff
}

// Whatever other functions you already have on Auth.
}

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(public authContext: AuthContextService) {}

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${this.authContext.getToken()}`
}
});
return next.handle(request);
}
}

关于angular - 无法实例化循环依赖! HttpClient ("[ERROR ->]") : in NgModule AppModule in ./AppModule@-1:-1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47449520/

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