0

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

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

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

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

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

在那里,我有src/MyService.ts一个Subject使用setInterval.

仅在您单击具有空单击处理程序的按钮时才会呈现其值Subjectsrc/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");
  }
}
4

1 回答 1

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 ,也许这会对您有所帮助

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

于 2016-03-14T04:18:43.403 回答