简体   繁体   中英

Server side rendering, angular 5 and subscriptions.

I'm trying to implement server side rendering on an angular 5 app. When the app is build and served everything works fine, however the source of the page isn't being rendered properly. I've discovered that if I use subscriptions and async pipes this solves the problem - what I see on the screen is also in the source. However, if I try to pipe the subscription and perform any actions with the return value the html is rendered correctly, however the source isn't.

This is how its implemented in the typescript when working correctly :

ngOnInit() {
  this.httpResponse$ = this._dataService
   .send(new BrochureRequest(this._stateService.params.propertyId));
}

This is the html

<div *ngIf="httpResponse$ | async as httpResponse; else loading">
  {{content goes here}}
</div>

In this case the info is displayed on the screen, ie the html waits for the async response - and crucially - all the data on the screen is reflected in the source.

However, in many cases I will want to perform some actions on the data returned from the service - SEO, ad targeting, etc... in which case I would like to do something like this

ngOnInit() {
    this.httpResponse$ = this._dataService
       .send(new BrochureRequest(this._stateService.params.propertyId)).pipe(
        tap((httpResponse) => {
            this.activeLink = 
            this._headerService.getActiveLink(this.httpResponse.Id);
            this._seoService.setSeoDetails(this.httpResponse.SeoDetails);
            // do more stuff
            return httpResponse;
        }));
  }

In this case, the info is displayed on screen as expected and all the other functions are called, however nothing in this component is appearing in the source. Its like the html was initially served without any of the data and not updated when the data was populated.

Any ideas why I'm not getting all my data in the source of the page? Is there a way I can delay any html rendering until the httpResponse is returned?

maybe you can use an event like ngAfterViewChecked? Read more about angular lifecycle hooks here https://angular.io/guide/lifecycle-hooks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM