【问题标题】:shared information between components through service not working通过服务不工作的组件之间共享信息
【发布时间】:2018-05-22 03:59:25
【问题描述】:

我在弄清楚这一点时遇到了一些麻烦,基本上我有一个headerTitleService,我希望能够在我的header 组件中动态设置标题,但是由于某种原因,当我设置标题时什么都没有显示?我没有收到任何错误,所以我似乎可以找出问题所在..

headerTitle.service.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class HeaderTitleService {
  title = new BehaviorSubject('');

  constructor() { }

  setTitle(title: string) {
    this.title.next(title);
  }
}

header.component.ts

import { Component, OnInit } from '@angular/core';
import { HeaderTitleService } from '../../../services/headerTitle.service'

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss'],
  providers: [HeaderTitleService]
})
export class HeaderComponent implements OnInit {
  title: string;

  constructor(
    private headerTitleService: HeaderTitleService
  ) { }

  ngOnInit() {
    this.headerTitleService.title.subscribe(updatedTitle => {
      this.title = updatedTitle;
    });
  }

}

header.component.html

<h1>{{title}}</h1>

home.component.ts

import { Component, OnInit } from '@angular/core';
import { HeaderTitleService } from '../../services/headerTitle.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
  providers: [HeaderTitleService]
})
export class HomeComponent implements OnInit {

  constructor(
    private headerTitleService: HeaderTitleService
  ) { }

  ngOnInit() {
    this.headerTitleService.setTitle('hello');
  }

}

【问题讨论】:

标签: javascript angular typescript


【解决方案1】:

HeaderTitleService 移动到模块的提供程序中。通过您的实施,您会在每个组件中收到 HeaderTitleService 的新实例。

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    每个组件中的providers: [HeaderTitleService] 行意味着每个组件将被分配一个HeaderTitleService,而不是它们之间的一个。

    要解决此问题,请从您的组件中删除 providers: [HeaderTitleService],并将其放在您的模块定义中:

    @NgModule({
      providers: [HeaderTitleService]
    })
    

    【讨论】:

      猜你喜欢
      • 2017-08-27
      • 1970-01-01
      • 2021-03-02
      • 1970-01-01
      • 2017-10-16
      • 2016-09-04
      • 2016-04-30
      相关资源
      最近更新 更多