Angular 4 and Tokens



我有一个为Angular 4编写的可注入身份验证服务。代码看起来类似于以下内容:

身份验证服务.ts

import { CookieService } from 'ngx-cookie';
import { Identity } from './auth.identity';
export function authInit(authService: AuthService): () => Promise<any> {
return (): Promise<any> => authService.checkAuthenticated();
}
@Injectable()
export class AuthService {
identity: Identity;
isAuthenticated:boolean = false;
apiUrl: string = 'https://myUrl/api';
constructor(private _http: HttpClient, private _cookieService: CookieService) {
this.identity = new Identity();
}
checkAuthenticated(): Promise<any> {
return new Promise((res, rej) => {
let identity = this._cookieService.getObject('myToken');
if (!!identity) {
this.setAuthenticated(identity);
}
});
}
login(username: string, password: string) {
let creds = {
username: username,
password: password
};
this._http.post<any>(this.apiUrl + '/auth/login', creds).subscribe(data => {
this.setAuthenticated(data);
});
}
logout() {
}
private setAuthenticated(data: any) {
this._cookieService.putObject('myToken', data);
this.isAuthenticated = true;
// hydrate identity object
}
}

身份验证模块.ts

import { NgModule, APP_INITIALIZER } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AuthService, authInit } from './auth.service';
@NgModule({
imports: [CommonModule],
providers: [
AuthService,
{
provide: APP_INITIALIZER,
useFactory: authInit,
deps: [AuthService],
multi: true
}
]
})
export class AuthModule { }

这个想法是,当应用程序加载时,我希望能够检查本地存储(cookie、sessionStorage或localStorage),看看该值是否存在。(构造函数中注释的if语句演示了这一点。)基于isAuthenticated属性,我希望能够显示特定的内容。

目前,如果我取消对构造函数中的行的注释,我将得到一个异常document.* is not defined。我知道这意味着什么。不幸的是,我不知道如何实现我的目标。

请记住,这是一个服务,而不是视图组件,因此没有可用的ngOnInit方法。

已编辑因此,我已按建议添加了工厂提供商。然而,我仍然得到异常:document is not defined

谢谢!

当您有一个服务需要在初始化其他所有服务之前运行时,您可以使用APP_INITIALIZER令牌(至少可以说,文档是稀疏的:)

要点是,在您的应用程序提供商阵列中,您添加了一个工厂提供商:

{
provide: APP_INITIALIZER,
useFactory: authInit,
deps: [AuthService],
multi: true
}

确保将provide设置为APP_INITIALIZER,并将multi值设置为true。authInit函数是一个工厂,它返回一个返回promise的函数。它必须返回一个承诺,而不是一个可观察的。它可能类似于:

export function authInit(authServ: AuthService) {
return () => authServ.check();
}

authServ.check()函数是您可以将当前已注释的逻辑放在服务中的地方(只需确保其结果返回promise)。以这种方式设置它将使该逻辑在应用程序加载时运行。

编辑:现在我看一下app.module.ts添加cookie服务的初始化并添加BrowserModule:

import { NgModule, APP_INITIALIZER } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';
import { CookieModule } from 'ngx-cookie';
import { AuthService, authInit } from './auth.service';
@NgModule({
imports: [BrowserModule, CommonModule, CookieModule.forRoot()],
providers: [
AuthService,
{
provide: APP_INITIALIZER,
useFactory: authInit,
deps: [AuthService],
multi: true
}
]
})
export class AuthModule { }

此外,请确保将ngx cookie添加到systemjs.config.js中(如果这是您用作加载程序的内容)。

最新更新