0

I am using Angular universal after making different modules and interceptor to handle server and browser request but home page is still loading twice. How to avoid this flicker. Here is the code I have used in interceptor


auth-interceptor.ts

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (request.method !== 'GET') {
  return next.handle(request);
}

const key: StateKey<string> = makeStateKey<string>(request.url);

if (isPlatformServer(this.platformId)) {

    return next.handle(request).pipe(tap((event) => {
      this.transferState.set(makeStateKey(request.url), (<HttpResponse<any>> event).body);
    }));
} else {
    const storedResponse: string = this.transferState.get(makeStateKey(request.url), null);
  if (storedResponse) {
    const response = new HttpResponse({body: storedResponse, status: 200});
    this.transferState.remove(key);
    return of(response);
   } else {
    return next.handle(request);
  }
 }
}

main.ts

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();
  if(window){
  window.console.log = function(){};
 }
}
  document.addEventListener('DOMContentLoaded', () => {
   platformBrowserDynamic().bootstrapModule(AppModule)
    .catch(err => console.log(err));
 });
  • Possible duplicate of [(Angular 6) Angular Universal - Not waiting on content API call](https://stackoverflow.com/questions/52270397/angular-6-angular-universal-not-waiting-on-content-api-call) – gorniv Jan 15 '19 at 10:18
  • you can also find this issue on https://github.com/angular/angular/issues/23427 it's open till now – Abhishek Bhardwaj Jan 17 '19 at 13:00

1 Answers1

0

After trying all the fix in my case it did not work ,I was still facing the flicker. that is because there was some *ngIf or *ngFor with async in the html template. So it when browser code is loaded it evaluates to false and delete all the prerendered elements by server. So make sure you prefetech your data using route resolvers and do not use any ngIf in html template I was facing another issue for which I had to apply a fix with preBoot if anyone has solution for that please suggest My client js files was not being loaded for that I had to do this in app.module.ts

PrebootModule.withConfig({ appRoot: 'app-root', replay: false }),

in app.component.ts

if (this.isBrowser) { this.replayer.replayAll(); this.appRef.isStable .pipe( takeUntil(this.ngUnsubscribe), filter(stable => stable), ).subscribe(() => { console.log('app is stable now'); this.replayer.replayAll(); }); }

Follow my answer and other solutions https://github.com/angular/angular/issues/23427