Angular 如何使用typescript获取页面标题?
我需要获取页面标题并将其写入变量。 我使用的是typescript代码:Angular 如何使用typescript获取页面标题?,angular,typescript,Angular,Typescript,我需要获取页面标题并将其写入变量。 我使用的是typescript代码: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'home', templateUrl: './home.component.html' }) export class HomeComponent implements OnInit { title: string; ngOnInit()
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'home',
templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit {
title: string;
ngOnInit() {
console.log("Title is " + this.title);
this.title === document.title;
}
}
但我在控制台上看到“标题未定义”
我还尝试:
title: string;
ngOnInit() {
this.title === this.titleService.getTitle();
console.log("Title is " + this.title);
}
public constructor(private titleService: Title) { }
getTitle() {
this.titleService.getTitle();
}
但结果是一样的。获取页面标题的正确方法是什么?您犯了几个错误
==
用于严格的相等比较,而不是设置变量的值(有关==
运算符的更多信息,请参见此处:) ngOnInit() {
this.title = document.title
console.log(this.title)
}
或:
您可以使用@angular/platform浏览器中的标题提供程序。请参阅但是您已经设置了document.title吗?是的,我已经在_Layoute.cshtml中设置了title。我正在使用.NET Core,但我认为这与这个问题无关,是吗?
==
?使用一个=
。我是说,如果你得到“未定义”,你可能没有设置它。document.title将为您提供在索引中设置的窗口标题。html@Vega我明白你刚才说得很清楚。感谢大家的快速帮助,原来这是新手犯的错误。这看起来很棒,但我在处理请求时遇到了一个未经处理的异常。异常:调用节点模块失败,错误:错误:未捕获(承诺中):引用错误:未定义文档引用错误:未定义文档如何定义它?第二种方法如何?关于titleService,老实说,我很惊讶第一个没有。在我这方面,它没有任何问题。
ngOnInit() {
this.title = this.titleService.getTitle();
console.log("Title is " + this.title);
}