我想显示页面的一个固定的导航栏的文件标题后进入到现场更新数据 - 可观察订阅
文件结构的每一页:
-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