使用Angular Universal的服务器端渲染(SSR)



为了创建服务器端应用程序模块,我使用了以下命令

ng add @nguniversal/express-engine

然后,我运行命令:npm run build:ssr,构建成功。

之后我跑了npm run serve:ssr,但得到以下错误

*****************-u:~/practice-angular$ npm run serve:ssr
> practice-angular@0.0.0 serve:ssr /home/bhavya/practice-angular
> node dist/practice-angular/server/main.js
/home/bhavya/practice-angular/dist/practice-angular/server/main.js:364478
redirectTo: localStorage.getItem('countryCode') || 'my'
^
ReferenceError: localStorage is not defined
at Object../src/app/app-routing.module.ts (/home/bhavya/practice-angular/dist/practice-angular/server/main.js:364478:21)
at __webpack_require__ (/home/bhavya/practice-angular/dist/practice-angular/server/main.js:20:30)
at Object../src/app/app.module.ts (/home/bhavya/practice-angular/dist/practice-angular/server/main.js:364599:30)
at __webpack_require__ (/home/bhavya/practice-angular/dist/practice-angular/server/main.js:20:30)
at Object../src/app/app.server.module.ts (/home/bhavya/practice-angular/dist/practice-angular/server/main.js:364718:22)
at __webpack_require__ (/home/bhavya/practice-angular/dist/practice-angular/server/main.js:20:30)
at Object../src/main.server.ts (/home/bhavya/practice-angular/dist/practice-angular/server/main.js:388159:27)
at __webpack_require__ (/home/bhavya/practice-angular/dist/practice-angular/server/main.js:20:30)
at Object../server.ts (/home/bhavya/practice-angular/dist/practice-angular/server/main.js:364353:23)
at __webpack_require__ (/home/bhavya/practice-angular/dist/practice-angular/server/main.js:20:30)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! practice-angular@0.0.0 serve:ssr: `node dist/practice-angular/server/main.js`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the practice-angular@0.0.0 serve:ssr script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     /home/bhavya/.npm/_logs/2021-09-03T08_32_02_929Z-debug.log

为了解决这个错误,我遵循了这个答案中提到的步骤。但是,我仍然无法解决这个问题。有谁能帮我解决这个问题吗?

当你的代码在服务器端执行时,浏览器中的一些API,比如localStoragesessionStorage和是不可用的。一个解决方案是注入PLATFORM_ID并使用isPlatformBrowser函数来访问这个API,只有当你在浏览器环境中。

import { Component, OnInit, Inject } from '@angular/core';
import { PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser} from '@angular/common';
@Component({
selector: 'your-component',
templateUrl: 'your-component.component.html',
styleUrls: ['your-component.component.css'],
})
export class YourComponent implements OnInit { 
constructor(@Inject(PLATFORM_ID) private _platformId: Object) {}
ngOnInit() {  
if (isPlatformBrowser(this._platformId)) {
// here you can access localStorage
} else {
// here you are on the server side and localStorage is not available
}
}
}

有一种方法可以在服务器端获得localStorage,例如使用node-localstorage,但随后你将在服务器上有一个localStorage,一个在浏览器中,如果你想共享数据,你必须找到同步它们的方法。

相关内容

  • 没有找到相关文章

最新更新