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?
With angular universal there should be no need to provide any external service as this is built in. (as echonax stated in the comments.)
Working example with this angular-universal fork. I guess it should be the same for your version of angular-universal.
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 takes care of setting a new title each time I navigate to a new route.
Hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With