使用 angular 2 titleService 和服务器端渲染调用 setTitle 时为 500

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

我在使用 angular 2 和 titleService 进行服务器端呈现时遇到问题。

我的代码是这样的

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...");
    }
}

这在使用客户端呈现时工作正常,但在重新加载页面时出现此错误:

异常:调用 Node 模块失败,出现错误:TypeError:无法在字符串 ''

上创建 属性 'title'

知道为什么会这样吗?

有了 angular universal,应该不需要提供任何外部服务,因为它是内置的。(如 echonax 在评论中所述。)

这个 angular-universal fork 的工作示例。我猜你的 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 负责在我每次导航到新路线时设置新标题。

希望对您有所帮助。

我想这可能是预料之中的,因为 titleService 与仅存在于浏览器中的元素交互。当阅读 "Universal Gotchas" 时,它清楚地表明您需要检查您是在客户端还是在浏览器中执行此操作。我希望 titleService 能够处理这些事情。但是检查客户端是否解决了问题。

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