客户端上的Angular SSR双重加载

时间:2020-05-30 23:36:00

标签: angular server-side-rendering angular-universal

我有一个Angular 7.2.16应用程序,由于SEO的原因,我按照https://angular.io/guide/universal中的说明安装了有角度的SSR。当我加载应用程序时,我注意到它已经加载了两次,即在客户端上,我的开头是html版本,而在客户端上执行javascript时,则显示了加载器重新加载了所有内容。

我检查了link,安装并仍然遇到相同的问题。我实现的方式认为该解决方案行不通。例如:

  ngOnInit()  {

    this.myItems = []
    this.spinner.show();
    this.httpClient.post(myurl).subscribe((val) => {
        this.myItems = val; // it has images that are shown on html through ngFor

        // add some og: metadata

        this.spinner.hide();
      }, (err) => {

         this.spinner.hide();
    });
  }

在客户端上,我在一开始就获得了完整的html版本...由于TransferHttpCacheModule,httpClient被拦截了,因此它不会再次调用它。由于我没有处于客户端或服务器端的任何条件,因此它似乎将执行两次,这会发生。

我要解决的是: 1.在具有适当的og元标记的服务器上 2.在客户端上,不要显示服务器上已经加载的内容,或者在客户端上时不显示任何内容。

任何想法都会有所帮助。

1 个答案:

答案 0 :(得分:0)

经过一些搜索并在@David的帮助下,这是解决方案:

import {Inject, Injectable, PLATFORM_ID} from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

...

constructor(@Inject(PLATFORM_ID) private _platformId: Object){}

  ngOnInit()  {

    this.myItems = []
    this.spinner.show();
    this.httpClient.post(myurl).subscribe((val) => {

        if (isPlatformBrowser(this._platformId)) {
            this.myItems = val; // it has images that are shown on html through ngFor
        }
        // add some og: metadata

        this.spinner.hide();
      }, (err) => {

         this.spinner.hide();
    });
  }