Angular 2组件通信服务无法正常工作

时间:2017-04-14 11:59:31

标签: angular

我试图通过服务在两个组件之间进行通信,但它不适合我,我不明白为什么。请指导我完成这个。我想在更改页面时更改页面标题栏。

服务

import {Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';
@Injectable()
export class UpdatePageTitleService {
  // Observable string sources
  private newTitleSource = new Subject<any>();
  // Observable string streams
  newTitle$ = this.newTitleSource.asObservable();

  changeTitle(title: any) {
    this.newTitleSource.next(title);
    console.log(this.newTitleSource);
  }


}

页面组件

import {Component, OnInit} from '@angular/core';

import {UpdatePageTitleService} from '../../../../share/updatePageTitle.service';

@Component({
  selector: 'customer-details',
  template: require('./customerDetails.html'),
  styleUrls: ['./customerDetails.scss'],
  providers: [UpdatePageTitleService]
})


export class CustomerDetails implements OnInit {

  constructor(private _updatePageTitleService: UpdatePageTitleService) {

  }

  ngOnInit() {
    this._updatePageTitleService.changeTitle('Details');
  }

}

标题页组件

import {Component} from '@angular/core';

import {UpdatePageTitleService} from '../../../share/updatePageTitle.service';

@Component({
  selector: 'ba-content-top',
  styles: [require('./titlePage.scss')],
  template: require('./titlePage.html'),
  providers: [UpdatePageTitleService]
})
export class TitlePage {

  public activePageTitle: string = '';

  constructor(private _updatePageTitleService: UpdatePageTitleService) {

    console.log("sankl");
    this.subscription = this._updatePageTitleService.newTitle$.subscribe(
      title => {
        console.log("title 1 " + title);
        this.activePageTitle = title;
      });
  }

}

1 个答案:

答案 0 :(得分:2)

  1. 请勿在{{1​​}}中添加服务。这将导致每个组件获取其自己的实例。而只是将其放在@Component.providers的{​​{1}}中。这将使它成为一个单身人士。

  2. 如果要缓存值,请在服务中使用@NgModule.providers而不是香草AppModule。请参阅Angular 2 special Observables (Subject / Behaviour subject / ReplaySubject)