带有Rx.subject的Angular2没有刷新视图

时间:2016-03-14 00:55:39

标签: angular rxjs angular2-changedetection

可能我错过了一些关于变化检测的Angular2概念。

我读过有关NgZones和ChangeDetectionStrategy但似乎没有解决我的问题。

案例是我有一个外部模块,我存储我的Observable并在一些组件中使用它们,当其中一个组件将某些内容更改为服务时,它会传播到其他组件。

我写了一个Plunker来帮助表达我的问题

http://plnkr.co/edit/ieHnm0ikBe4BR5w6O1XE?p=preview

在那里,我有src/MyService.ts我使用Subject模拟setInterval并且不断更改数据。

Subject中使用了src/app.ts,只有当您单击带有空单击处理程序的按钮时,才会呈现其值。

的src / MyService.ts

import * as Rx from 'rxjs/Rx';

let global = {};

// The Observable
global.subject = new Rx.Subject();

// Updates value every second
setInterval(() => global.subject.next(Date.now()), 1000);

export var Global = global;

的src / app.ts

import {Component} from 'angular2/core'
import {Global} from './myService'

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <button (click)="clickMe()">Click me</button>
      <p>Current time: {{subject | async}}</p>
    </div>
  `,
  directives: []
})
export class App {
  public subject = Global.subject;
  constructor() {
    this.name = 'Angular2'
  }

  public clickMe () {
    console.log("I'm just a click event that do nothing");
  }
}

1 个答案:

答案 0 :(得分:0)

我不知道这是不是你要找的。

Plunker

import {Component, ChangeDetectorRef} from 'angular2/core'
import {Global} from './myService'

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <button (click)="clickMe()">Click me</button>
      <p>Current time: {{subject | async}}</p>
    </div>
  `,
  directives: []
})

export class App {

  public subject = Global.subject;

  constructor(public ref: ChangeDetectorRef) {
    this.name = 'Angular2';

    setInterval(() => {
                this.ref.detectChanges();
              }, 1000);
  }

  public clickMe () {
    console.log("I'm just a click event that do nothing");
  }
}

您可能还想看一下。

import {Component} from 'angular2/core'
import {GlobalSR} from './myService'

@Component({
  selector: 'my-app',
  providers: [GlobalSR],
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <button (click)="clickMe()">Click me</button>
      <p>Current time: {{subject | async}}</p>
    </div>
  `,
  directives: []
})

export class App {

  public subject;

  constructor(public globalSR: GlobalSR) {
    this.name = 'Angular2';
    this.subject = globalSR.global.subject;

  }

  public clickMe () {
    console.log("I'm just a click event that do nothing");
  }
}

Plunker

如果您喜欢全球分享,也许这会对您有所帮助 angular2-global-service-provider

我不知道你想做什么。我希望它能帮到你,对不起我的英语