简体   繁体   English

服务器端渲染,角度5和订阅。

[英]Server side rendering, angular 5 and subscriptions.

I'm trying to implement server side rendering on an angular 5 app. 我正在尝试在angular 5应用程序上实现服务器端渲染。 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. 但是,如果我尝试通过管道传递订阅并使用返回值执行任何操作,则html会正确显示,但是源却不正确。

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 这是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. 在这种情况下,信息显示在屏幕上,即html等待异步响应-至关重要的是-屏幕上的所有数据都反映在源中。

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 但是,在许多情况下,我会希望对从服务返回的数据执行某些操作-SEO,广告定位等...在这种情况下,我想做这样的事情

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. 就像html最初是在没有任何数据的情况下提供的,并且在填充数据时并未更新。

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? 有没有办法我可以延迟任何HTML渲染,直到返回httpResponse

maybe you can use an event like ngAfterViewChecked? 也许您可以使用ngAfterViewChecked之类的事件? Read more about angular lifecycle hooks here https://angular.io/guide/lifecycle-hooks 在此处阅读有关角度生命周期挂钩的更多信息https://angular.io/guide/lifecycle-hooks

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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