简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM