title: Angular Universal does not wait for api/http request before render
body: <p>I have a brand new angular universal project that seems to pretender all the HTML (which is good).
  However, I am trying to make an API call to my .NET server which is a standard API build with the weatherforecast API.</p>
  <p>The API calls and it works great, but it only happens after my web app has switched from pre render to csr. see example 1.</p>
  <p><strong>Example 1</strong></p>
  <p><a href="https://i.stack.imgur.com/TzaIT.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/TzaIT.gif" alt="enter image description here" /></a></p>
  <p>if I disable javascript on the page this is what I get</p>
  <p><a href="https://i.stack.imgur.com/LbnzT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LbnzT.png" alt="enter image description here" /></a></p>
  <p>and this is the HTML code</p>
  <pre><code>  &lt;div style=&quot;padding: 5rem&quot;&gt;
      &lt;h1&gt;TEST&lt;/h1&gt;
      &lt;h2&gt;{{ this.SampleMessage }}&lt;/h2&gt;
      &lt;div *ngFor=&quot;let product of weather$ | async&quot;&gt;
        &lt;p&gt;{{ this.product.summary }}&lt;/p&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  </code></pre>
  <hr />
  <p><strong>app.component.ts</strong></p>
  <pre><code>import { AppService } from './app.service';
  import { Component, OnInit } from '@angular/core';
  import { Observable } from 'rxjs';
  
  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
  })
  export class AppComponent implements OnInit {
    title = 'ModernaMediaAngular';
    text:string = &quot;test&quot;
  
    weather$: Observable&lt;any&gt;;
    SampleMessage=&quot;Example of Angular Async Pipe&quot;;    
    
    constructor(private as: AppService, ) {}
  
    async ngOnInit() {
      await this.getWeatherAsyncPipe();
      //non async
      this.as.getWeather().subscribe( res =&gt;
        {
          this.text = res[0].date;
          console.log(&quot;got resolution&quot;);
          console.log(res);
          console.log(this.text);
        }
      );
  
  
    }
    public async getWeatherAsyncPipe() {    
          this.SampleMessage=&quot;Example of Angular Async Pipe&quot;;    
          this.weather$ = await this.as.getWeatherAsync();    
          console.log(this.weather$);
        }    
  }
  </code></pre>
  <hr />
  <p><strong>app.service.ts</strong></p>
  <pre><code>import { environment } from './../environments/environment';
  import { HttpClient, HttpHeaders } from '@angular/common/http';
  import { Injectable } from '@angular/core';
  import { Observable } from 'rxjs';
  
  @Injectable({
    providedIn: 'root'
  })
  export class AppService {
    public waeatherUrl = environment.url + '/api/weatherForecast/get'
    constructor(private http: HttpClient) { }
  
    getWeather() : Observable&lt;object&gt; {
      const headers = new HttpHeaders(
        {'Content-Type': 'application/json',
        'Access-Control-Allow-Origin' : 'http://localhost:4200'
      }
        );
      var x = this.http.get(this.waeatherUrl, {headers: headers}).pipe();
      console.log(x);
      return x;
    }
  
    public getWeatherAsync():Observable&lt;any&gt; {
      return this.http.get&lt;any[]&gt;(this.waeatherUrl);    
    }
  }
  </code></pre>
  <hr />
  <p><strong>app.module.ts</strong></p>
  <pre><code>import { BrowserStateInterceptor } from './interceptors/browserstate.interceptor';
  import { BrowserModule } from '@angular/platform-browser';
  import { NgModule } from '@angular/core';
  
  import { AppRoutingModule } from './app-routing.module';
  import { AppComponent } from './app.component';
  import { HttpClientModule } from '@angular/common/http';
  
  import { TransferHttpCacheModule } from '@nguniversal/common'
  
  @NgModule({
    declarations: [
      AppComponent
    ],
    imports: [
      BrowserModule.withServerTransition({ appId: 'serverApp' }),
      TransferHttpCacheModule,
      AppRoutingModule,
      HttpClientModule,
    ],
    bootstrap: [AppComponent]
  })
  export class AppModule {}
  </code></pre>
  <p><strong>app.server.module</strong></p>
  <pre><code>import { NgModule } from '@angular/core';
  import { ServerModule, ServerTransferStateModule } from '@angular/platform-server';
  import { AppModule } from './app.module';
  import { AppComponent } from './app.component';
  
  @NgModule({
    imports: [
      AppModule,
      ServerModule,
      ServerTransferStateModule
    ],
    bootstrap: [AppComponent],
  })
  export class AppServerModule {}
  </code></pre>
  <hr />
  <p><strong>main.ts</strong></p>
  <pre><code>import { enableProdMode } from '@angular/core';
  import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
  
  import { AppModule } from './app/app.module';
  import { environment } from './environments/environment';
  
  if (environment.production) {
    enableProdMode();
  }
  
  document.addEventListener('DOMContentLoaded', () =&gt; {
    platformBrowserDynamic().bootstrapModule(AppModule)
    .catch(err =&gt; console.error(err));
    console.log(&quot;DOMCONTENTLOADED&quot;);
  });
  </code></pre>
  <hr />
  <p>I also get what I think is a cors error whenever the prerendering tries to fetch from the API.</p>
  <pre><code>chunk {main} main.js, main.js.map (main) 66.3 kB [initial] [rendered]
  chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 141 kB [initial] [rendered]
  chunk {runtime} runtime.js, runtime.js.map (runtime) 6.15 kB [entry] [rendered]
  chunk {styles} styles.css, styles.css.map (styles) 118 bytes [initial] [rendered]
  chunk {vendor} vendor.js, vendor.js.map (vendor) 2.8 MB [initial] [rendered]
  Date: 2021-03-15T14:26:38.903Z - Hash: a20337e49cf8941fcbf6 - Time: 12492ms
  Hash: af451acd21594faf190e
  Time: 19059ms
  Built at: 2021-03-15 15:26:41
        Asset      Size  Chunks                          Chunk Names
      main.js  6.44 MiB    main  [emitted]        [big]  main
  main.js.map  6.99 MiB    main  [emitted] [dev]         main
  Entrypoint main [big] = main.js main.js.map
  chunk {main} main.js, main.js.map (main) 6.08 MiB [entry] [rendered]
  
  Compiled successfully.
  ** Angular Universal Live Development Server is listening on http://localhost:4200, open your browser on http://localhost:4200 **
  Observable {
    _isScalar: false,
    source: Observable {
      _isScalar: false,
      source: Observable {
        _isScalar: false,
        source: [Observable],
        operator: [MergeMapOperator]
      },
      operator: FilterOperator { predicate: [Function], thisArg: undefined }
    },
    operator: MapOperator { project: [Function], thisArg: undefined }
  }
  
  Observable {
    _isScalar: false,
    source: Observable {
      _isScalar: false,
      source: Observable {
        _isScalar: false,
        source: [Observable],
        operator: [MergeMapOperator]
      },
      operator: FilterOperator { predicate: [Function], thisArg: undefined }
    },
    operator: MapOperator { project: [Function], thisArg: undefined }
  }
  
  ERROR HttpErrorResponse {
    headers: HttpHeaders {
      normalizedNames: Map {},
      lazyUpdate: null,
      headers: Map {}
    },
    status: 0,
    statusText: 'Unknown Error',
    url: 'https://localhost:5001/api/weatherForecast/get',
    ok: false,
    name: 'HttpErrorResponse',
    message: 'Http failure response for https://localhost:5001/api/weatherForecast/get: 0 Unknown Error',
    error: ProgressEvent {
      type: 'error',
      target: XMLHttpRequest {
        onloadstart: null,
        onprogress: null,
        onabort: null,
        onerror: null,
        onload: null,
        ontimeout: null,
        onloadend: null,
        _listeners: [Object],
        onreadystatechange: null,
        _anonymous: undefined,
        readyState: 4,
        response: null,
        responseText: '',
        responseType: 'text',
        responseURL: '',
        status: 0,
        statusText: '',
        timeout: 0,
        upload: [XMLHttpRequestUpload],
        _method: 'GET',
        _url: [Url],
        _sync: false,
        _headers: [Object],
        _loweredHeaders: [Object],
        _mimeOverride: null,
        _request: null,
        _response: null,
        _responseParts: null,
        _responseHeaders: null,
        _aborting: null,
        _error: null,
        _loadedBytes: 0,
        _totalBytes: 0,
        _lengthComputable: false
      },
      currentTarget: XMLHttpRequest {
        onloadstart: null,
        onprogress: null,
        onabort: null,
        onerror: null,
        onload: null,
        ontimeout: null,
        onloadend: null,
        _listeners: [Object],
        onreadystatechange: null,
        _anonymous: undefined,
        readyState: 4,
        response: null,
        responseText: '',
        responseType: 'text',
        responseURL: '',
        status: 0,
        statusText: '',
        timeout: 0,
        upload: [XMLHttpRequestUpload],
        _method: 'GET',
        _url: [Url],
        _sync: false,
        _headers: [Object],
        _loweredHeaders: [Object],
        _mimeOverride: null,
        _request: null,
        _response: null,
        _responseParts: null,
        _responseHeaders: null,
        _aborting: null,
        _error: null,
        _loadedBytes: 0,
        _totalBytes: 0,
        _lengthComputable: false
      },
      lengthComputable: false,
      loaded: 0,
      total: 0
    }
  }
  
  ERROR HttpErrorResponse {
    headers: HttpHeaders {
      normalizedNames: Map {},
      lazyUpdate: null,
      headers: Map {}
    },
    status: 0,
    statusText: 'Unknown Error',
    url: 'https://localhost:5001/api/weatherForecast/get',
    ok: false,
    name: 'HttpErrorResponse',
    message: 'Http failure response for https://localhost:5001/api/weatherForecast/get: 0 Unknown Error',
    error: ProgressEvent {
      type: 'error',
      target: XMLHttpRequest {
        onloadstart: null,
        onprogress: null,
        onabort: null,
        onerror: null,
        onload: null,
        ontimeout: null,
        onloadend: null,
        _listeners: [Object],
        onreadystatechange: null,
        _anonymous: undefined,
        readyState: 4,
        response: null,
        responseText: '',
        responseType: 'text',
        responseURL: '',
        status: 0,
        statusText: '',
        timeout: 0,
        upload: [XMLHttpRequestUpload],
        _method: 'GET',
        _url: [Url],
        _sync: false,
        _headers: [Object],
        _loweredHeaders: [Object],
        _mimeOverride: null,
        _request: null,
        _response: null,
        _responseParts: null,
        _responseHeaders: null,
        _aborting: null,
        _error: null,
        _loadedBytes: 0,
        _totalBytes: 0,
        _lengthComputable: false
      },
      currentTarget: XMLHttpRequest {
        onloadstart: null,
        onprogress: null,
        onabort: null,
        onerror: null,
        onload: null,
        ontimeout: null,
        onloadend: null,
        _listeners: [Object],
        onreadystatechange: null,
        _anonymous: undefined,
        readyState: 4,
        response: null,
        responseText: '',
        responseType: 'text',
        responseURL: '',
        status: 0,
        statusText: '',
        timeout: 0,
        upload: [XMLHttpRequestUpload],
        _method: 'GET',
        _url: [Url],
        _sync: false,
        _headers: [Object],
        _loweredHeaders: [Object],
        _mimeOverride: null,
        _request: null,
        _response: null,
        _responseParts: null,
        _responseHeaders: null,
        _aborting: null,
        _error: null,
        _loadedBytes: 0,
        _totalBytes: 0,
        _lengthComputable: false
      },
      lengthComputable: false,
      loaded: 0,
      total: 0
    }
  }
  </code></pre>
  <p>but no errors in console:</p>
  <p><a href="https://i.stack.imgur.com/nVaCZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nVaCZ.png" alt="enter image description here" /></a></p>
  <p>In <strong>startup.cs</strong> in my .NET 5 project I have configured cors:</p>
  <pre><code>public void ConfigureServices(IServiceCollection services) {
      services.AddControllers();
      services.AddSwaggerGen(c =&gt; {
          c.SwaggerDoc(&quot;v1&quot;, new OpenApiInfo { Title = &quot;ModernaMediaDotNet&quot;, Version = &quot;v1&quot; });
          });
      services.AddCors();
  }
  </code></pre>
  <p>and in public void Configure(IApplicationBuilder app, IWebHostEnvironment env)</p>
  <pre><code>app.UseRouting();
  app.UseCors(x =&gt; x
              .AllowAnyOrigin()
              .AllowAnyMethod()
              .AllowAnyHeader()
              .SetIsOriginAllowed(origin =&gt; true) // allow any origin
              );
  </code></pre>