解决方法
话虽这么说,这就是我设法在我的应用程序中提供cookie的方式,当它呈现在服务器端时:
app.server.module.ts:
// ... import { Request } from 'express'; import { REQUEST } from '@nguniversal/express-engine/tokens'; @Injectable() export class RequestCookies { constructor(@Inject(REQUEST) private request: Request) {} get cookies() { return !!this.request.headers.cookie ? this.request.headers.cookie : null; } } @NgModule({ imports: [ // ... ],providers: [ CookieService,{ provide: 'req',useClass: RequestCookies } ],bootstrap: [AppComponent] }) export class AppServerModule {}
app.module.ts :(有些人可能称之为app.browser.module.ts)
@NgModule({ declarations: [ // ... ],imports: [ // ... ],{ provide: 'req',useValue: null } ],bootstrap: [AppComponent] }) export class AppModule {}
cookie.service.ts:
import { Inject,Injectable } from '@angular/core'; @Injectable() export class CookieService { private cookieStore = {}; constructor( @Inject('req') private readonly req: any,) { if (this.req !== null) { this.parseCookies(this.req.cookies); } else { this.parseCookies(document.cookie); } } public parseCookies(cookies) { this.cookieStore = {}; if (!!cookies === false) { return; } let cookiesArr = cookies.split(';'); for (const cookie of cookiesArr) { const cookieArr = cookie.split('='); this.cookieStore[cookieArr[0]] = cookieArr[1]; } } get(key: string) { return !!this.cookieStore[key] ? this.cookieStore[key] : null; } }
any.component.ts:
// ... constructor( private cookieService: CookieService ) {} needMyCookie() { const userCookie = this.cookieService.get('user'); }
确保你> npm install express @ nguniversal / express-engine
附:我开始看这个回购:https://github.com/angular/universal-starter/tree/master/cli用于服务器端渲染,只做了自己的cookie部分(不包括在那里).
这个回购跟随你链接的普遍故事,但超越了.如果您只是遵循通用故事,它会说:
Lazy loading is not yet supported
但是,如果您尝试使用我发布的链接,您会发现服务器上的延迟加载模块也是RENDERED!我不知道密钥是什么,也许它与server.js文件中的代码和@nguniversal / module-map-ngfactory-loader有关.
我尝试过:
CLI版本1.4.2和Angular版本:4.4.1
这是我在浏览器中禁用javascript时得到的:
我的旋转木马项目间距是这样的,因为它们实际上缩放到90%.我在onInit上的项目上有一个zoomIn动画.在服务器渲染视图上,我将它们强制设置为90%,这样它们在第一次加载时就不会出现100%,然后在客户端启动后,将它们设置为90到100的动画.
此外,如果有人遇到这个答案,并注意到屏幕截图中的视口宽度的引用,在主导航链接下面的代码块中 – 如果他们想知道 – 这是我的WindowService:
import { Injectable,PLATFORM_ID,Inject } from '@angular/core'; import { isPlatformBrowser,isPlatformServer } from '@angular/common'; @Injectable() export class WindowService { constructor( @Inject(PLATFORM_ID) private readonly platformId: any,) {} get width() { if (isPlatformBrowser(this.platformId)) { return window.innerWidth; } else { return 'Not available server-side!'; // return null; } } }
只需将它添加到app.module.ts和app.server.module.ts中的providers:[]数组即可.
这里需要注意的另一件事是我正在使用Node with Express.如果您正在使用其他框架,例如Hapi或其他任何框架,我不知道这样做.