我想顯示頁面的一個固定的導航欄的文件標題後進入到現場更新數據 - 可觀察訂閱
文件結構的每一頁:
-navbar.ts (where I display the title, import current title from service)
-titles.service.ts (store the current title)
-component_one.ts (Send title 1 to service)
-component_two.ts (Send title 2 to service)
navbar.ts文件
import { Component, OnInit,} from '@angular/core';
import { Subscription } from "rxjs";
import {TitleService} from './titles.service';
import {component_one} from '../component_one';
import {component_two} from '../component_two';
@Component({
selector: '[navbar]',
template: require('./navbar.html'),
providers:[TitleService, component_one, component_two]
})
export class Navbar implements OnInit {
title_page: any;
_subscription: any;
constructor(public com_one: component_one, public _titleService:TitleService, public com_two: component_two){
this.title_page = _titleService.title_page;
this._subscription = _titleService.titleChange.subscribe((value) => {
this.title_page = value;
}); //it's ok?
}
ngOnDestroy() {
this._subscription.unsubscribe();
}
}
titles.service.ts
個import {Component, Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Subject } from 'rxjs/Subject';
import { Subscription } from "rxjs";
@Injectable()
export class TitleService {
title_page: any;
titleChange: Subject<string> = new Subject<string>(); //it is ok?
constructor() {
this.title_page = "default title string";
}
change(title){
this.title_page = title;
this.titleChange.next(this.title_page); //I think is not working
}
}
component_one.ts文件 (負荷後這個頁面,我想顯示在導航欄的html文件'TITLE OF COMPONENT ONE'
)
import {Component} from '@angular/core';
import {TitleService} from '../core/navbar/titles.service';
@Component({
selector: '[component_one]',
template: require('./component_one.html')
providers: [TitleService]
})
export class component_one{
title_page: any;
constructor(public http: Http, public _titleService: TitleService){
this.title_page = _titleService.title_page;
this.changeMyTitle(); //Update Title
}
changeMyTitle() {
this._titleService.change('TITLE OF COMPONENT ONE');
}
}
component_two.ts文件(與不同的標題字符串component_one,負載該頁面後,我想表明'TITLE OF COMPONENT two'
導航欄上的HTML文件)
import {Component} from '@angular/core';
import {TitleService} from '../core/navbar/titles.service';
@Component({
selector: '[component_two]',
template: require('./component_one.html')
providers: [TitleService]
})
export class component_two{
title_page: any;
constructor(public http: Http, public _titleService: TitleService){
this.title_page = _titleService.title_page;
this.changeMyTitle(); //Update Title
}
changeMyTitle() {
this._titleService.change('TITLE OF COMPONENT TWO');
}
}
進入到第一頁(組件之一)仍呈現'TITLE OF COMPONENT TWO'
後,我在做什麼錯?
只是加:供應商是通過模型共享,所以,如果您在模塊中提供服務,則所有孩子都將訪問相同的服務實例。但是,如果您以兩個模塊提供服務,則每個模塊都有一個服務實例。爲了使這兩個模塊具有相同的實例,您需要在封裝其他兩個模塊的模塊中提供該服務,例如app模塊或您選擇的另一個模塊。 – vinagreti
感謝所有的快速回復,可悲的是我不能使用NgModule,有沒有辦法避免NgModule? – Louis
@Louis你使用的是舊版本嗎? – echonax