Search code examples
angularserver-side-rendering

Angular SSR hangs if OnInit subscribes to an observable


I have a simple page that subscribes to an observable. The entire page hangs and it does not render. What is wrong here?

 ngOnInit () {
    const query = this.activatedRoute.snapshot.queryParams;
    if (!query.code) {
        this.router.navigate(['/auth/login']);
    } else {
        this.checkGoogleCodeAndRedirect(query);
    }

}

private checkGoogleCodeAndRedirect (query: { [K: string]: string }) {
    this.authStateService.authenticateWithGoogle(query.code).subscribe(
        (x) => {
            if (query.state) {
                 return;
            }
            return this.router.navigate(['/']);
        },
        (error) => {
            return this.router.navigate(['/auth/login']);
        },
    );
}

Solution

  • Maybe it's due to SSR, where the observable does not complete, so that page remains loading, instead execute this logic only for the browser.

    import { inject, Inject, Injectable, PLATFORM_ID } from '@angular/core';
    import { isPlatformBrowser, isPlatformServer } from '@angular/common';
    ...
    
    ...
    platformId = inject(PLATFORM_ID);
    ...
    
    ...
    ngOnInit () {
      if(isPlatformBrowser(this.platformId)) {
        const query = this.activatedRoute.snapshot.queryParams;
        if (!query.code) {
            this.router.navigate(['/auth/login']);
        } else {
            this.checkGoogleCodeAndRedirect(query);
        }
      }
    }
    
    private checkGoogleCodeAndRedirect (query: { [K: string]: string }) {
        this.authStateService.authenticateWithGoogle(query.code).subscribe(
            (x) => {
                if (query.state) {
                     return;
                }
                return this.router.navigate(['/']);
            },
            (error) => {
                return this.router.navigate(['/auth/login']);
            },
        );
    }