gpt4 book ai didi

javascript - Angular 4服务构造函数问题

转载 作者:行者123 更新时间:2023-12-03 03:17:51 25 4
gpt4 key购买 nike

我的 authservice 有问题。如果我在构造函数内发出 http 请求,它会被调用 259 次。如果我删除 http 调用,它就会被调用一次。我使用共享模块来提供该服务的唯一实例。

Angular 版本:4.4.4

Console print

这是我的共享模块:

export const providers = [
AuthService,
DataStorageService,
];

@NgModule({
imports: [
CommonModule,
FormsModule,
HttpClientModule,
ReactiveFormsModule,
InfiniteScrollModule,
TruncateModule
],
declarations: [
FooterComponent,
PhotoListComponent,
GalleryListComponent,
],
exports: [
FooterComponent,
PhotoListComponent,
GalleryListComponent,
InfiniteScrollModule,

],
providers: [

]})

export class SharedModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
providers: [...providers]
};
}
}

还有我的 AuthService:

@Injectable()
export class AuthService {

public session: Subject<SessionModel> = new Subject<SessionModel>();
private cachedSession: SessionModel = new SessionModel(null, null, false);
private apiUrl = 'http://localhost:8080/Galleo/user/login';


constructor(private cookieSrv: CookieService,
private http: HttpClient) {
console.log('constructor called');
if (this.cookieSrv.get('system-g-unx-data')) {
const cook = atob(this.cookieSrv.get('system-g-unx-data')).split('||');
const username = cook[0];
const password = cook[1];
this.login(username, password);
}
}

// login method, call REST API and store cookie into user Browser
login(username: string, password: string) {

const user: UserModel = new UserModel();
user.userName = username;
user.password = password;

const headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');

this.http.post<UserModel>(this.apiUrl, user, {observe: 'response', headers: headers}).subscribe(
(response) => {
console.dir(response);
this.cachedSession.user = response.body;
this.cachedSession.token = response.headers.get('Authorization');
this.cachedSession.isAuthenticated = true;
this.session.next(this.cachedSession);
this.cookieSrv.put('system-g-unx-data', btoa(username + '||' + password));
},
(error) => {
console.dir(error);
this.session.next(null);
}
);
}
}

谢谢!

编辑:我发现了问题。来自 AuthInterceptor。当我尝试获取授权 token 时,它会启动无限循环:

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
private authService: AuthService;
constructor(private injector: Injector) {}

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('Intercepted!', req);
this.authService = this.injector.get(AuthService);

const request = req.clone({
setHeaders: {
Authorization: `${this.authService.getSession().token}`
}
});

return next.handle(request);

}
}

现在如何在不使用注入(inject)器的情况下恢复拦截器内的 authService ?

最终编辑:我想出了如何从我的 authService 获取 token 而不进行无限循环。问题是我用于将 token 添加到每个请求的授权 header 的 HttpInterceptor。在我的 AuthService 构造函数中,我调用了发出 http 请求的登录方法。循环:拦截器 => 身份验证服务 => HTTP 客户端,然后再次拦截器

所以,现在我在拦截器中进行一些检查,例如:

Injectable()
export class AuthInterceptor implements HttpInterceptor {
private authService: AuthService;
constructor(private injector: Injector) { }

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

// If login method called skip and continue request
if (req.url.includes('login')) {
return next.handle(req);
}

// If request don't have the Authorization Header, add the token to the header
if (!req.headers.has('Authorization')) {
this.authService = this.injector.get(AuthService);
const request = req.clone({
setHeaders: {
Authorization: `${this.authService.getSession().token}`
}
});
return next.handle(request);
}

return next.handle(req);
}

也许可以帮助遇到同样问题的人。PS:检查后需要调用注入(inject)器

感谢您的帮助!

最佳答案

创建一个 core/core.module.ts,将其导入到 app.module.ts 中

import { CommonModule } from '@angular/common';
import {
ModuleWithProviders, NgModule,
Optional, SkipSelf
} from '@angular/core';


import { AuthGuard } from '../guards/auth.guard';
import { AuthService } from '../services/auth.service';

@NgModule({
imports: [CommonModule],
declarations: [],
exports: [],
providers: [AuthGuard, AuthService]
})

export class CoreModule {

constructor( @Optional() @SkipSelf() parentModule: CoreModule) {
if (parentModule) {
throw new Error(
'CoreModule is already loaded. Import it in the AppModule only');
}
}

static forRoot(): ModuleWithProviders {
return {
ngModule: CoreModule,
providers: [
AuthService,
AuthGuard,
]
};
}
}

有一个检查以确保它只加载一次。

app.module.ts

import {CoreModule} from './core/core.module';

@NgModule({
declarations: [
],
imports: [
CoreModule.forRoot(),
],
providers: [

],
bootstrap: [AppComponent]
})

它在“核心模块”下的文档中被引用为单例 https://angular.io/guide/ngmodule

关于javascript - Angular 4服务构造函数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46692056/

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