Search code examples
javascriptnode.jsangularangular2-services

500 when calling setTitle using angular 2 titleService and server side rendering


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 when reloading the page I get this error:

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

Any ideas why this occurs?


Solution

  • I guess this might be expected since the titleService interacts with element only present in the browser. When reading the "Universal Gotchas" it clearly status that you need to check if you are on the client or in the browser when doing this. I expected the titleService to handle such things though. However checking if client solved the problem.

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