角度4服务构造问题
我的authservice有问题。如果我在构造函数中创建一个http请求,它被称为259次。 如果我删除了http调用,它会被调用一次。我使用共享模块来提供该服务的唯一实例。角度4服务构造问题
角版本:4.4.4
这里是我的sharedModule:
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。当我尝试获得授权令牌它开始一个无限循环:
@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);
}
}
现在我该怎么恢复里面拦截器authService不使用注射器?
FINAL EDIT: 我想出了如何从我的authService获取令牌而不发生无限循环。 问题是我用于为每个请求添加令牌到Authorization Header的HttpInterceptor。 在我AuthService构造我打电话的登录方法,使一个HTTP请求.. LOOP:拦截器=> AUTH SERVICE => 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:注射器需要在检查后调用
感谢您的帮助!
,你在你的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,
]
};
}
}
一次导入它有一个检查,以确保它仅加载一次创建一个核心/ core.module.ts。
app.module。TS
import {CoreModule} from './core/core.module';
@NgModule({
declarations: [
],
imports: [
CoreModule.forRoot(),
],
providers: [
],
bootstrap: [AppComponent]
})
其作为在“核心模块” https://angular.io/guide/ngmodule
这不起作用..是同样的事情..你试图做一个http请求里面?我需要声明的http客户端? –
在docs一个单引用的“在ES6类(或打字原稿在这种情况下)的构造方法是一类本身的特征,而不是一个Angular功能“:https://toddmotto.com/angular-constructor-ngoninit-lifecycle-hook 考虑使用'constructor'主要用于依赖注入,使用'ngOnInit'代替你的逻辑 –
ngOnInit不被调用服务... –