2017-07-20 40 views
2

我需要把页面标题写入一个变量。 我使用打字稿代码:如何使用打字稿获取页面标题?

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

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

+0

但是您是否设置了document.title呢? – Vega

+0

是的,我在_Layoute.cshtml中设置了标题。我正在使用.NET Core,但我不认为它与问题有关,是吗? – kendzi

+1

'==='?使用一个'='。 –

回答

1

你犯了几个错误。

  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); 
} 
+0

这看起来不错,但我得到了 处理请求时发生未处理的异常。 异常:调用节点模块失败,出现错误:错误:未捕获(承诺):ReferenceError:文档未定义 ReferenceError:文档未定义 我应该如何定义它? – kendzi

+0

第二种方法呢?用'titleService'? –

+0

是的,第二种方法正在工作。 – kendzi