500 when calling setTitle using angular 2 titleService and server side

I have a problem with server side rendering using angular 2 and titleService.

My code looks like this

import { Component } from '@angular/core';
import { BrowserModule, Title } from '@angular/platform-browser';
import { Router } from '@angular/router';

@Component({
    selector: 'app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    providers: [Title]
})

export class AppComponent {
    constructor(private titleService: Title) {
        titleService.setTitle("Setting the title...");
    }
}

      

This works fine using client side rendering, but on page reload I get this error:

Exception: Call to Node module failed with error: TypeError: unable to create property 'title' on string ''

Any ideas why this is happening?

+3


source to share


2 answers


I guess this is to be expected since titleService interacts with an element that is only present in the browser. Reading "Universal Gotchas" clearly states that you need to check if you are on the client or in the browser while doing this. I expected the titleService to handle things like this. However, checking if the client has resolved the problem.



Se: https://github.com/angular/universal

0


source


With angular generic, there should be no need to provide any external service as it is built in. (like echonax pointed out in the comments.)

Working example with this angular-universal fork . I think it should be the same for your angular-universal version.

app.component.ts



import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { Meta, Title } from '@angular/platform-browser';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  constructor(private _router: Router, private _meta: Meta, private _title: Title) { }

  ngOnInit() {
    this._router.events.subscribe((event) => {      
      if (event instanceof NavigationEnd) {
        switch (event.urlAfterRedirects) {
          case '/':
            this._title.setTitle('title goes here');
            this._meta.updateTag({ name: 'description', content: 'same goes for meta content' });
            break;
          case '/another-route':
            this._title.setTitle('Another title');
            this._meta.updateTag({ name: 'description', content: 'You get the idea' });
            break;

        }
      }
    });
  }
}

      

NavigationEnd configures a new title every time it navigates to a new route.

Hope it helps.

+1


source







All Articles