Angular Universal Prerendering with httpClient for getting data from /static/data.json content
Asked Answered
F

1

6

I'm just trying to prerender an component with Angular Universal which fetches data with httpClient from the /static folder within the app itself.

  1. How do I use httpClient correctly in Angular Universal?
  2. Is it possible to access static assets from within the project and fetch them with httpClient while prerendering?

I guess the file is not accessible since the application is not running on any server while prerendering. The get path is referred relativ. Fetching the file later on remote server works, however the "remoteserver" is not available during prerendering or? How can this be made working?

I do get an Error [ERROR] which is caused by the httpClient.get(). Catching the error the error message is empty.

basically I do have a service

doReqeust() = {
  return this.httpClient.get("./static/get.json")
}

and in the compoonent

onInit() {
  this.data = this.myService.doRequest();
}

and the view than it is bound through async pipe

{{ data.response.title | async }}

with static being a static folder within the project.

Fairish answered 18/1, 2018 at 17:24 Comment(0)
I
4

You can access static files in the assets folder

Note that when using angular universal, request URLs must be absolute. The request URL will be the one of the webserver doing the prerendering (e.g. http://localhost:4000.

Service.ts

import {Inject, Injectable, Optional, PLATFORM_ID} from '@angular/core';
import {isPlatformBrowser} from "@angular/common";
import {HttpClient} from "@angular/common/http";

constructor(private http: HttpClient, @Inject(PLATFORM_ID) private platformId: Object, 
@Optional() @Inject('serverUrl') protected serverUrl: string)
  {
  }


doRequest()
{
    let baseUrl = isPlatformBrowser(this.platformId)? '' : this.serverUrl;
    return this.http.get(baseUrl + '/assets/static/file.json');

You need to provide the value for serverUrl. This should be done in your backend. Assuming that you are using nodejs

server.ts

 extraProviders: [
  //...
  {
    provide: 'serverUrl',
    useValue: `http://localhost:${NODEJS_PORT}`
  },
Infighting answered 19/1, 2018 at 11:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.