1

I have working server side rendering project followed by Angular Universal guide. Eveything working fine except when I am navigating to other ulrs i still see first page (login page) source when hiting "view page source".

Any idea what this issue can be?

p.s. conten generated by prerender.ts also generates login screen source.

3
  • If you want to see the current DOM, you can use developer tools from Chrome, right click and press inspect. This way you'll the current generated DOM. Commented Nov 6, 2017 at 13:49
  • Did you try to disabled javascript to see if the server side rendering is really working? Commented Nov 8, 2017 at 14:30
  • Hmm no, but I will. Thanks Commented Nov 9, 2017 at 15:01

3 Answers 3

1

View Page Source shows originally loaded HTML, later DOM is modified by angular, but it has no effect on originally loaded HTML.

Sign up to request clarification or add additional context in comments.

3 Comments

And how search spiders then get modified html and its structure if it is not changing? Because if they can read changed HTML then server side rendering does not make sense...
As Radu Diță told in his comment, open dev tools and browse Elements tab
Yes i know, but you can open dev tools without server side rendering and you will see all output. But search spiders cannot open dev tools this is what server side rendering is all about...
0

I recently had this problem too. It was something to do with the server proxy on an Apache server not rendering pages on other urls. However, everything was working on my localhost server.

example.com (rendering)
example.com/faq (rendering)
example.com/faq/general (not rendering)

If you are using Apache, configure your proxy settings in your virtualhost file

<VirtualHost *:80>
 ServerName example.com
 DocumentRoot /your/apache/files/htdocs

 ProxyRequests Off
 ProxyPreserveHost On
 ProxyVia Full
 <Proxy *>
  Require all granted
 </Proxy>

<Location /*>
      ProxyPass http://127.0.0.1:3000
      ProxyPassReverse http://127.0.0.1:3000
</Location>
<Location /faq/*>
      ProxyPass http://127.0.0.1:3000
      ProxyPassReverse http://127.0.0.1:3000
</Location>

</VirtualHost>

Restart your server and it should come up on your view page source.

3 Comments

I solved this problem. The problem was not real one but more my missunderstanding. Routes were under authorization so i had to remvoe authorization for server side rendering. However there i snot much sense of SSR for authorized routes :) I just did not think that SSR does real REST API calls to get stuff renedered correctly.
Hey @VytautasPranskunas by authorization you mean auth guard or server-side authentication?
Under API authentication
0

This can be achieved using resolvers

Using Resolver method

So I know that this question isn't answered much. But let me put light on this scenario.

Resolver

A data provider class can be used with the router to resolve data during navigation. The interface defines a resolve() method that is invoked right after the ResolveStart router event. The router waits for the data to be resolved before the route is finally activated.

How it works

Create a resolver within your component / architecture based. In your General-Landing-Component.ts subscribe to the resolver function and invoke the API calls to view page on SSR.

General-Landing-Resolver.ts

import { Inject, Injectable, PLATFORM_ID } from '@angular/core';
import { ActivatedRouteSnapshot,  Resolve,  RouterStateSnapshot,  Router,  ActivatedRoute,} from '@angular/router';

import { Observable, of } from 'rxjs';
import { ContentfulService } from '../../contentful/services/contentful.service';
import { ContentfulResponse } from '../../contentful/interfaces/contentful-response';
import { map } from 'rxjs/operators';
import { isPlatformBrowser } from '@angular/common';
@Injectable({
  providedIn: 'root',
})
export class generalLandingResolver implements Resolve<ContentfulResponse> {
  urlPath: any;
  responseData: any;
  private isBrowser: boolean = false;
  constructor(
    private contentfulService: ContentfulService,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    @Inject(PLATFORM_ID) private platformId: Object
  ) {
    this.isBrowser = isPlatformBrowser(platformId);
  }
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<any> {
    const tree = this.router.parseUrl(state.url);
    const children = tree.root.children.primary;
    const segments = children.segments[1].path;
    this.urlPath = segments;

    return this.contentfulService.generalLandingPageBySlug(this.urlPath).pipe(
      map((response) => {
        if (this.isBrowser) {
          sessionStorage.setItem('response', response);
        }
      })
    );
  }
}

General-Landing-Component.ts

import { Component, OnInit, Inject, PLATFORM_ID } from '@angular/core';
import { Router } from '@angular/router';
import { combineLatest, EMPTY, Observable } from 'rxjs';
import { ContentfulResponse } from '../../contentful/interfaces/contentful-response';
import { ContentfulService } from '../../contentful/services/contentful.service';
import { DOCUMENT, isPlatformBrowser } from '@angular/common';

@Component({
  selector: 'app-general-landing-page',
  templateUrl: './general-landing-page.component.html',
  styleUrls: ['./general-landing-page.component.scss'],
})
export class GeneralLandingPageComponent implements OnInit {
  contentfulResponse$!: Observable<ContentfulResponse>;
  componentschoosen: any;
  componentsResults: any;
  urlPath: any;
  siteURL: any;
  siteURLpath: any;
  private isBrowser: boolean = false;

  constructor(
    private contentfulService: ContentfulService,
    private router: Router,
    @Inject(DOCUMENT) private dom: Document,
    @Inject(PLATFORM_ID) private platformId: Object
  ) {
    this.isBrowser = isPlatformBrowser(platformId);
  }

  ngOnInit(): void {
    this.siteURL = new URL(this.dom.URL);
    this.siteURLpath = this.siteURL?.pathname;
    this.urlPath = this.siteURLpath.split('/')[2];

    this.contentfulService
      .generalLandingPageBySlug(this.urlPath)
      .subscribe((_) => {
        if (this.contentfulService.generalLandingResponse == null) {
          this.contentfulService.generalLandingResponse = sessionStorage.getItem(
            'response'
          );
        }

        if (
          this.contentfulService.generalLandingResponse.includes(
            '__typename ...'
          )
        ) {
          this.contentfulResponse$ = this.contentfulService.generalLandingPageProcessedData(
            this.contentfulService.generalLandingResponse,
            this.urlPath
          );
        }
      });

    this.router.routeReuseStrategy.shouldReuseRoute = function () {
      return false;
    };
  }

  ngAfterContentChecked(): void {
    if (this.isBrowser) {
      sessionStorage.removeItem('response');
    }
  }
}

Import the resolver file

General-Landing-Component.module.ts

import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CoreModule } from '../../core/core.module';
import { GeneralLandingPageComponent } from './general-landing-page.component';
import { generalLandingResolver } from './general-landing-page.resolver';

const routes: Routes = [
  {
    path: '',
    component: GeneralLandingPageComponent,
    resolve: { generalContent: generalLandingResolver },
  },
];

@NgModule({
  declarations: [GeneralLandingPageComponent],
  imports: [CommonModule, CoreModule, [RouterModule.forChild(routes)]],
})
export class GeneralLandingPageModule {}

General-Landing-Component.html

<ng-container *ngIf="contentfulResponse$ | async as data">
  <ng-container *ngFor="let component of data?.components">
    <app-contentful
      [template]="component.pageData.__typename"
      [component]="component.pageData"
    ></app-contentful>
  </ng-container>
</ng-container>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.