gpt4 book ai didi

angular - 如何使用 typescript 获取页面标题?

转载 作者:太空狗 更新时间:2023-10-29 18:30:57 24 4
gpt4 key购买 nike

我需要获取页面标题并将其写入变量。我正在使用 typescript 代码:

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();
}

但结果是一样的。获取页面标题的正确方法是什么?

最佳答案

你犯了几个错误。

  1. === 用于严格相等比较,而不是用于设置变量的值(有关 === 运算符的更多信息可以在这里找到:Difference between == and === in JavaScript ).
  2. 您首先要显示变量,然后尝试“设置”(查看第 1 点)它的值。

将您的代码更改为:

 ngOnInit() {
this.title = document.title
console.log(this.title)
}

或:

ngOnInit() {
this.title = this.titleService.getTitle();
console.log("Title is " + this.title);
}

关于angular - 如何使用 typescript 获取页面标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45224974/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com