Search code examples
node.jsangulartypescriptangular-universalangular-router

Angular HttpClient issue in resolver


Using Angular 2 with AOT compilation enabled (Angular universal), in a custom resolver I'm getting the error..

Uncaught (in promise): Error Error: Uncaught (in promise): Error

The problem seems to be isolated to when I return the result of a HttpClient call (which is just a simple number).

If I switch off server side rendering this all works correctly. Below is an extract of the code.

constructor(private httpClient : HttpClient)
{

}

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): number | Observable<number> | Promise<number> {

    try{
        return this.httpClient.get<number>(`/api/something/getnumber`);
    }catch(e){
         console.log(e);              
    }
    return -1;
}

Is this a fundamental issue in server side rendering?, or am I just missing some critical configuration that you need with server side rendering enabled?


Solution

  • It has to do with the fact that you are getting non-json data as a result. Add {responseType: 'text'} to your call to specify this.

    return this.httpClient.get<number>(`/api/something/getnumber`, {responseType: 'text'});
    

    See also the documentation Requesting non-JSON data

    Not all APIs return JSON data. Suppose you want to read a text file on the server. You have to tell HttpClient that you expect a textual response: