ken*_*dzi 5 typescript angular
我需要获取页面标题并将其写入变量。我正在使用打字稿代码:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
但我在控制台上收到“标题未定义”。
我也尝试过:
title: string;
ngOnInit() {
this.title === this.titleService.getTitle();
console.log("Title is " + this.title);
}
public constructor(private titleService: Title) { }
getTitle() {
this.titleService.getTitle();
}
Run Code Online (Sandbox Code Playgroud)
但结果是一样的。获取页面标题的正确方法是什么?
你已经犯了几个错误。
===用于严格相等比较,而不是用于设置变量的值(有关===运算符的更多信息可以在此处找到:Difference Between == and === in JavaScript)。将您的代码更改为:
ngOnInit() {
this.title = document.title
console.log(this.title)
}
Run Code Online (Sandbox Code Playgroud)
或者:
ngOnInit() {
this.title = this.titleService.getTitle();
console.log("Title is " + this.title);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10185 次 |
| 最近记录: |