我下载了用于 nodejs 的通用启动器,并开始从旧的 angular-rc4 迁移我的网站。但是当我必须实现身份验证时(在我的情况下,它是存储在 localStorage 中的 JWT),服务器没有 localStorage 和 cookie,因此 Angular 仅在客户端上呈现。
我已遵循本指南:https ://github.com/angular/universal-starter/issues/148但它没有用。
下面是我的代码:
身份验证.services.ts
import { OpaqueToken } from '@angular/core';
export let AUTH_SERVICES = new OpaqueToken('auth.services');
export interface AuthenticationService {
forgotPassword(email: any);
isAuthenticated();
getCurrentUser();
refreshToken();
signin(user : any);
signout();
signup(user : any);
}
server.authentication.ts
import { Injectable } from '@angular/core';
import { AuthenticationService } from './authentication.services';
@Injectable()
export class ServerAuthenticationService implements AuthenticationService {
forgotPassword(email: any) {
throw new Error('Forgot password cannot be called while doing server side rendering');
}
isAuthenticated() {
return false;
}
getCurrentUser(){
if(this.isAuthenticated()) {
return {};
}
return {};
}
refreshToken() {
}
signin(user : any) {
throw new Error('Login cannot be called while doing server side rendering');
}
signout() {
throw new Error('Logout cannot be called while doing server side rendering');
}
signup(user : any) {
throw new Error('Sign up cannot be called while doing server side rendering');
}
}
clientAuthentication.services.ts
@Injectable()
export class UserService implements AuthenticationService {
forgotPassword(email: any){
// client implementation
}
isAuthenticated() {
// client implementation
}
getCurrentUser() {
// client implementation
}
refreshToken() {
// client implementation
}
signin(user : any){
// client implementation
}
signout(){
// client implementation
}
signup(user : any) {
// client implementation
}
}
app.browser.module.ts
@NgModule({
bootstrap: [ AppComponent ],
declarations: [ AppComponent ],
imports: [
UniversalModule, // BrowserModule, HttpModule, and JsonpModule are included
FormsModule,
SharedModule,
HomeModule,
AboutModule,
NavbarModule,
AppRoutingModule
],
providers: [
{ provide: 'isBrowser', useValue: isBrowser },
{ provide: 'isNode', useValue: isNode },
{ provide: 'LRU', useFactory: getLRU, deps: [] },
{ provide: AUTH_SERVICES, useFactory: UserService},
CacheService
]
})
app.node.module.ts
@NgModule({
bootstrap: [ AppComponent ],
declarations: [ AppComponent ],
imports: [
UniversalModule, // NodeModule, NodeHttpModule, and NodeJsonpModule are included
FormsModule,
SharedModule,
HomeModule,
AboutModule,
NavbarModule,
AppRoutingModule
],
providers: [
{ provide: 'isBrowser', useValue: isBrowser },
{ provide: 'isNode', useValue: isNode },
{
provide: 'LRU',
useFactory: getLRU,
deps: [
[new Inject('LRU'), new Optional(), new SkipSelf()]
]
},
{ provide: AUTH_SERVICES, useFactory: ServerAuthenticationService },
CacheService
]
})
那么如何在通过路由器转换导航到客户端上的该页面时与通过浏览器刷新在服务器上导航到相同的页面输出?
提前致谢