2017-07-26 205 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');