简体   繁体   English

Angular Universal不呈现来自API请求的数据

[英]Angular Universal does not render data from API Requests

My Angular Universal application is only rendering the HTML in the template, but not any variables or data that is loaded from API requests. 我的Angular Universal应用程序仅呈现模板中的HTML,而不呈现从API请求中加载的任何变量或数据。

I created a very simple test component: 我创建了一个非常简单的测试组件:

HTML: HTML:

<h1>ObjectID: #{{user?.id}}</h1>   

Typescript: 打字稿:

export class TestComponent implements OnInit {

  user: User
  constructor(private userService: UserService) { }

  ngOnInit() {
    this.userService.getUser(1).subscribe(user => this.user = user)
  }
}

The results from this if I look in the source of my page will be <h1>ObjectID: #</h1> . 如果查看页面的源代码,结果将是<h1>ObjectID: #</h1> I'm using the Universal Starter . 我正在使用Universal Starter Isn't the Angular Universal server suppose to wait for the ngOnInit() to finish loading? Angular Universal服务器不是应该等待ngOnInit()完成加载吗?

The issue was that I was serving my Angular app and my API app from 2 separate Docker containers, and the Server-Side-Rendered NodeJS app was trying to do the HTTP calls to the public url of the API container -- the problem with this is that a Docker container does not know the public url (eg 0.0.0.0:8000) of the other containers, it only knows the container names (eg http://backend ). 问题是我正在从2个单独的Docker容器中提供Angular应用程序和API应用程序,并且服务器端渲染的NodeJS应用程序正在尝试对API容器的公共URL进行HTTP调用-这是问题所在是Docker容器不知道其他容器的公共URL(例如0.0.0.0:8000),它只知道容器名称(例如http:// backend )。

This is only an issue during development, not during production because then it uses a real public domain. 这只是开发过程中的问题,而不是生产过程中的问题,因为它使用了真正的公共领域。

The solution I did was to add a alias in my etc/hosts file on my local computer to 0.0.0.0, and then also adding the same alias in my docker-compose.yml file. 我执行的解决方案是在本地计算机的etc/hosts文件中添加一个别名至0.0.0.0,然后在docker-compose.yml文件中添加相同的别名。 So both my browser, and the container, can access the API on a custom hostname. 因此,我的浏览器和容器都可以通过自定义主机名访问API。

etc/hosts on local machine 等/本地计算机上的主机

0.0.0.0 api.local

docker-compose.yml docker-compose.yml

services:
  ...
  backend:
    ...
    networks:
      default:
        aliases:
          - "api.local"

All HTTP calls during development from both the client and the server side rendered app is done to http://api.local/ 在开发过程中,从客户端和服务器端渲染的应用程序进行的所有HTTP调用均已完成http://api.local/

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

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