简体   繁体   中英

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.

I created a very simple test component:

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> . I'm using the Universal Starter . Isn't the Angular Universal server suppose to wait for the ngOnInit() to finish loading?

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 ).

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. So both my browser, and the container, can access the API on a custom hostname.

etc/hosts on local machine

0.0.0.0 api.local

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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