skip to Main Content

I know that Angular Universal is still in development. So I have thought about using Angular Universal for a web app that regularly pulls data from an external API server (about every 10 seconds via the Http service). This data is then displayed on the web app.

I have come across several problems that I haven’t found an easy solution for yet:

  1. Angular Universal obviously needs data from the API server to prerender the page. I don’t want to query the API server from nodeJS every time the web app HTML is requested. It would be enough if the nodeJS server “behaved” exactly like one client web app instance and queries the API server every 10 seconds too, “caches” this data in intervals of 10s and uses it to render the HTML.
  2. The client web app stores the data from the API server in some private member variable. This member variable is then used to build the HTML from it with ngFor, bindings etc. But this member variable is empty/undefined at the beginning of course. I don’t want the client web app to wipe the prerendered HTML on startup, because that would kind of defeat some of the ideas of Angular Universal (not SEO, but reduced loading time).

I hope you understand what I’m trying to achieve here. Do you have an idea how to approach this, or is there even an “official” way to do that? I am sure I am not the only one trying to do something like that.

2

Answers


  1. Angular Universal doesn’t know if your code is server code or client code, it just take your app and try to render it on the server. but as you mentioned there is a time you want the server to act differently from the client. For example if you have a function that you want that Angular Universal will skip put this line of code at the top of the function body.

    if (typeof window === "undefined") return;
    

    Or if you have a scenario that you need to server to do something differently from the client do this

    if (typeof window === "undefined") {
        // server code
    } else {
       // client code
    };
    
    Login or Signup to reply.
  2. Angular Universal have two constants isNode & IsBrowser

    if(isNode){
    
       // it's Node Server
    
    } else {
      //it's Browser
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search