【问题标题】:How to update the updated service value in all the components using angular2如何使用 angular2 更新所有组件中的更新服务值
【发布时间】:2018-03-07 12:10:45
【问题描述】:

我们有两个组件共享相同的服务,我们更改了一个组件中的服务值,该值我也需要更新其他组件。

app.component.ts

import { Component } from '@angular/core';
import {ConfigurationService} from './first.servvice';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers : [ConfigurationService]
})
export class AppComponent {
  title : boolean;
  constructor(private configurationService:ConfigurationService){
    this.title = this.configurationService.toggle;
  }


}



@Component({
  selector: 'app-root1',
  templateUrl: './app.component1.html',
   providers : [ConfigurationService]
})
export class AppComponent1 {
  title : boolean;
  constructor(private configurationService:ConfigurationService){
      this.title = this.configurationService.toggle;
  }
  change(){
    this.configurationService.toggle = ! this.configurationService.toggle;
    this.title = this.configurationService.toggle;
  }
}

服务.ts

import {Injectable} from "@angular/core";

@Injectable()
export class ConfigurationService {
 toggle :boolean = false;
}

当我们更新其他组件中的服务值时,我需要更新服务值。

代码:

https://plnkr.co/edit/LtrflSk7bICMC2xmacS5?p=preview

【问题讨论】:

标签: angular angular2-services angular2-directives


【解决方案1】:

使用 rxjs Subject。在您的服务中,进行以下更改:

import {Subject} from "rxjs";

@Injectable()
export class ConfigurationService {
    toggle: Subject<boolean> = new Subject<boolean>();
}

.. 无论您在哪里使用此服务中的值,请订阅toggle

this.configurationService.toggle.subscribe(value => this.title = value);

..当你想改变/更新它时,你可以做以下事情:

this.configurationService.toggle.next(!this.configurationService.toggle);

链接到你updated plunker

【讨论】:

  • 如果我尝试在两个组件中显示 {{title}} ,我会变空。在我调用“change() 方法标题值后,只在一个组件中更新,而不是两个
  • 我的感觉是“this.configurationService.toggle.subscribe(value => this.title = value);”它不能正常工作
猜你喜欢
  • 1970-01-01
  • 2018-06-09
  • 2016-08-31
  • 2019-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-02
相关资源
最近更新 更多