2017-07-26 220 views
0

我试图让我的应用程序的每个页面在头部设置标题标记。 我尽可能地将其作为一项服务进行了设置,但其行为与预期不符。Imprlementing Angular 2服务

title.service.ts:

import { Injectable } from '@angular/core'; 
import { TitleService } from '../../../services/title.service'; 

@Injectable() 
export class { 


    constructor() { 
    }; 


    appName = "My App"; 

    public setTitle(newTitle: string) { 
     console.log("!!!"); 
     this.setTitle(this.appName + " - " + newTitle); 
    } 
} 

login.component.ts: '!MyApp的 - 登录'

import { Component, OnInit } from '@angular/core'; 
import { Title } from '@angular/platform-browser'; 

export class BaseLoginComponent implements OnInit { 
    constructor(
     private titleService: TitleService 
     ) { 
    } 

    this.titleService.setTitle('Login!'); 

非但没有的我简单地'登录'

所以,奇怪的是,我**能够设置标题,我只是绕过服务。

它永远不会调用setTitle()。更重要的是,我想看看是否title.service甚至被加载,所以我试图插入一个console.log(“loaded ..?”);。它在该行上抛出了一堆错误 - 主要是期待分号。

+0

是在功能的setTitle是无穷递归? –

+0

代码已更新。无论如何,app.component中的这段代码看起来没有必要,所以我已经删除了它。 – DaveC426913

+1

@ DaveC426913你甚至没有在代码中包含类名。它压倒Angular的默认标题服务吗? – echonax

回答

0

好吧,我明白我要去哪儿了。有一个现有的 setTitle服务;我不需要自己做。

它的字面意思一样简单:

app.module.ts:

import { BrowserModule, Title } from '@angular/platform-browser'; 

@NgModule({ 
    providers[ 
     Title 
    ] 
}) 

login.component.ts:

import { Title }  from '@angular/platform-browser'; 

constructor(private title: Title){} 

this.title.setTitle('MyApp - Login');