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() {
        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/

相关文章:

javascript - 获取 'Could Not Be Found' 错误 : Custom Pipe in Angular 2 App

Typescript - 在对象的键上循环时类型缩小

javascript - nickperkinslondon angular treeview expand_all() 问题

angular - azure AD 和图形访问 - Angular 前端和 Laravel php 后端

angular - 如何在模态窗口 [ANGULAR 5] 内创建路由?

angular - 在 angular2 中使用 [(ngModel)] 时初始化空白表单

TypeScript:扩展模块时如何编写定义?

javascript - 如何在 Angular 6 中处理多个 http 请求

angular - npm 运行构建 :ssr does not work in angular 8

javascript - 未捕获( promise ): TypeError: Cannot read property 'component' of null