我有一个Angular项目,如果我在没有Angular Universal命令的情况下构建,它可以正常工作"ng服务开发:ssr">
当我使用这个命令来构建Universal时,我得到了这个错误:
Error: src/app/widgets/location/google-places/google-places.component.ts:87:29 - error TS2304: Cannot find name 'google'.
87 this.sessionToken = new google.maps.places.AutocompleteSessionToken();
当我尝试构建时,我遇到了这个错误,但经过一番搜索,我知道我只需要添加@types,并且在没有Universal的情况下在我的项目中运行良好。
但现在我想用Universal构建,这在过去也遇到了同样的错误,我该怎么办?
"devDependencies": {
"@angular-devkit/build-angular": "~12.1.4",
"@angular/cli": "~12.1.4",
"@angular/compiler-cli": "~12.1.0",
"@nguniversal/builders": "^12.1.0",
"@types/body-scroll-lock": "^3.1.0",
"@types/crypto-js": "^4.0.2",
"@types/express": "^4.17.0",
"@types/googlemaps": "^3.43.3",
"@types/jasmine": "~3.8.0",
"@types/node": "^12.11.1",
"jasmine-core": "~3.8.0",
"karma": "~6.3.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.0.3",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "~1.7.0",
"typescript": "~4.3.2"
}
我已经有@类型了。
原因是你不能访问全局对象,比如window,SSR中的文档,我认为你从window.google.收到了这个谷歌对象
所以最好只在浏览器中运行代码:
export class Service {
constructor(
@Inject(PLATFORM_ID) private platformId: string,
){}
method(){
if (isPlatformBrowser(this.platformId)) {
// place your code about google
}
}
}