1

In Angular 2+ only way to redirect to an external Url is to use the window.location.href = '...';.

How to redirect to an external URL in Angular2

However this gives following error when Angular is running in SSR mode.

ERROR ReferenceError: window is not defined

Is there anyway I can avoid this error during Server side rendering of the page.

Amitabh
  • 59,111
  • 42
  • 110
  • 159
  • This is also a problem if you're using in order to try and data bind with a url. It appends that url onto the angular app url as if youre using router. Interested in how to solve a problem like this with inline templates – Jonathan Corrin Jan 17 '18 at 20:06

1 Answers1

1

You'll need to send provide your angular app from the server with an object that you will modify in the angular code

For instance, in your server code inject an extra parameter, which will be modified in the angular app if you need a redirection.

 let respData = {redirectUrl: ''};
//....
 extraProviders: [
 {
    provide: 'httpResponseData',
    useValue: respData,
  }

In the angular application, inject that extra parameter in the constructor of the component/service where you want to specify the redirect url

constructor(@Inject(PLATFORM_ID) private platformId: Object, @Optional() @Inject('httpResponseData') private httpResponseData: any)
{
//...
}

When you want to redirect, use the new parameter instead of the window object

redirect(url: string)
{
    if(isPlatformBrowser(this.platformId))
    {
         window.location.href = url;
    }
    else
    {
         this.httpResponseData.redirectUrl = url;
    }
}

Finally, in your web server, check the value of the respData.redirectUrl property and redirect if the url is set

David
  • 33,444
  • 11
  • 80
  • 118