简体   繁体   English

如何在angular 7服务器端渲染中处理cookie

[英]How handle cookies in angular 7 server side rendering

I recently implemented SSR on my angular 7 project for SEO. 我最近在我的SEO的angular 7项目中实现了SSR。 I've been using ngx-cookie-service. 我一直在使用ngx-cookie-service。 I noticed an error when i first ran the app with SSR, culprit was this.cookieService.check when attempting to render the app. 当我第一次使用SSR运行应用程序时,我注意到一个错误,当尝试渲染应用程序时,罪魁祸首是this.cookieService.check。 In one of my components I have in ngOnInit(), it performs a method call that does the following: 在ngOnInit()中的其中一个组件中,它执行方法调用,该方法执行以下操作:

const exists = this.cookieService.check('cookiename');
if (exists) {
  showSpoilerCookieValue = this.cookieService.get('cookiename');
}

Temporarily i have removed the method that calls this logic to get the app to work. 暂时我已经删除了调用此逻辑的方法来使应用程序正常工作。

How can i get this to work? 我该如何工作? Is there a better NPM package out there for cookies? 是否有更好的NPM Cookie包?

I saw posts recommending ngx-utils/cookies. 我看到了推荐ngx-utils / cookie的帖子。 However it doesn't appear to support @nguniversal/express-engine . 但是,它似乎不支持@nguniversal/express-engine There is a pull request fix this git pull that allows express-engine . 这个git pull有一个请求请求修复,它允许express-engine for ngx-utils/cookies 用于ngx-utils / cookie

I stupidly wasted time getting the ngx-utils/cookies , applying the pull, upgrading package.json with the latest angular, but didn't end up getting to test it as i ran out of time. 我愚蠢地浪费了时间来获取ngx-utils / cookies ,应用拉动,以最新的角度升级package.json,但是由于时间用完了,最终并没有对其进行测试。 I should have done more research before going down this path. 在走这条路之前,我应该做更多的研究。

Is there a package cookie that will work for angular 7 SSR? 是否有适用于angular 7 SSR的软件包cookie? im on angular 7.1 right now. 我现在在7.1角上。

Using 使用

@ngx-utils/cookies

You need to check if you are in the browser or not 您需要检查您是否在浏览器中

import { isPlatformBrowser } from '@angular/common';
import { CookiesService } from '@ngx-utils/cookies';
constructor(
    private cookieService: CookiesService,
    @Inject(PLATFORM_ID) private platformId: Object
) {}

  isLoggedIn(): Promise<boolean> {
   return new Promise<any>((resolve, reject) => {
    if (isPlatformBrowser(this.platformId)) {
      // get the cookie here
      this.cookieService.get('token')
      resolve('something here') 
    }
  });
 }

Hope this helps!! 希望这可以帮助!! ... same thing if you want to use window object you will need to do ...如果您想使用窗口对象,则需要做同样的事情

...
if (isPlatformBrowser(this.platformId)) {
    window.scrollTop() // or whatever you do with window object   
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM