Angular应用程序自动调用所有api,而无需在浏览器中打开



当使用sudo npm run serve_dev:ssr服务angular应用程序时,它应该等待urllocalhost:4400在浏览器中打开,然后调用所有提到的api在UI中显示。但问题是,当应用程序提供服务时,它会自动调用所有api,而无需在浏览器中打开localhost url。

我想知道为什么会发生这种情况?我错过了什么吗?当应用程序部署在服务器上时,这个问题会导致502坏网关错误。

在做SSR时需要注意一些事情。在运行任何操作之前,您可能需要检查从哪个平台进行调用。例如,下面的代码:

import { Component, PLATFORM_ID, Inject } from '@angular/core';
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
@Component({
selector: 'app-postfeed',
templateUrl: './postfeed.component.html',
styleUrls: ['./postfeed.component.css']
})
export class PostfeedComponent implements OnInit {
constructor(@Inject(PLATFORM_ID) private platform: Object) { }
ngOnInit() {
if (isPlatformBrowser(this.platform)) {
// here you can run any browser specific code, like:
window.alert('This will run only in the browser!');
}
}
}

这段代码是一个检查平台是否为浏览器的示例。如果你的调用使用isPlatformBrowser,你可以延迟浏览器的API调用。

谢谢!

相关内容

最新更新