[英]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...");
}
}
使用客户端渲染工作正常,但重新加载页面时出现此错误:
例外:调用节点模块失败并显示错误:TypeError:无法在字符串''上创建属性'title'
有没有想过为什么会这样?
对于角度通用,不需要提供任何外部服务,因为它是内置的。(正如echonax在评论中所述。)
这个角度通用叉子的工作示例。 我猜你的角度通用版应该是一样的。
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可以处理这些事情。 但是检查客户是否解决了问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.