Angular 2 - 所有订阅组件

时间:2016-12-06 09:23:27

标签: events angular rxjs observable subscription

对这些事件的 ReplySubject Observables 订阅有点麻烦。

在这项服务中,我创建了一个每30秒触发一次的Observable并从API中提取消息,然后

export class BspecReaderApiService {

  public MessageListObservable: Observable<MessageList>;
  public messageListReplySubject: ReplaySubject<MessageList>;

  constructor() {

    // set a messageList reply subject that returns an updated list of messages
    // every minute
    this.messageListReplySubject = new ReplaySubject<MessageList>(1);

    Observable.interval(30000).subscribe((i) => {
      if (this.messageAutoRefresh) {

        (...)

        // gets messages ml from API and trigger event
        this.messageListReplySubject.next(ml);

      }
    });

  }

这很有效,然后我有这三个不同的组件订阅了replySubject,如下所示:

MessageBox组件:

@Component({
  selector: '.messagesBox',
  templateUrl: 'messages-box.component.html',
  styleUrls: ['messages-box.component.css'],
  providers: [BspecReaderApiService]
})
export class MessagesBoxComponent implements OnInit {

  public messageList: MessageList;

  constructor(private _bspec: BspecReaderApiService) {

    // subscribe to message list event
    console.log('messageBox subscribe to messageList');
    this._bspec.messageListReplySubject.subscribe(ml => {
      this.messageList = ml;
      console.log('messageBox received messageList', this.messageList);
    });
  }

  public ngOnInit() { }

}

app.component:

export class AppComponent {

  public messageList: MessageList;

  constructor(
    private _bspec: BspecReaderApiService,
  ) {

    (...)

    // subscribe to message list event
    console.log('app component subscribe to messageList');
    this._bspec.messageListReplySubject.subscribe(ml => {
      this.messageList = ml;
      console.log('app component received messageList', this.messageList);
    });
  }

ETC。

现在,当我运行应用程序时,我进入控制台:

app.component.ts:37          app component subscribe to messageList
messages-box.component.ts:27 messageBox subscribe to messageList
home.component.ts:53         home component subscribe to messageList

(...) 

app component received messageList MessageList {newUser: false, startedSession: true, openedProject: false, messages: Array[0], diagnostics: Diagnostics…}

这是问题,只有app组件收到了messageList,而不是其他两个组件!为什么并非所有三个组件都从事件中检索messageList?

编辑

更多信息,这是我的package.json,我的角度版本和rxjs版本:

  "dependencies": {
    "@angular/common": "2.1.0",
    "@angular/compiler": "2.1.0",
    "@angular/compiler-cli": "2.1.0",
    "@angular/core": "2.1.0",
    "@angular/forms": "2.1.0",
    "@angular/http": "2.1.0",
    "@angular/platform-browser": "2.1.0",
    "@angular/platform-browser-dynamic": "2.1.0",
    "@angular/platform-server": "2.1.0",
    "@angular/router": "3.0.0",
    "angular2-jwt": "0.1.23",
    "core-js": "2.4.1",
    "ng2-cookies": "1.0.1",
    "rxjs": "5.0.0-beta.12",
    "sweetalert2": "4.0.10",
    "ts-helpers": "^1.1.1",
    "zone.js": "0.6.23"
  },

0 个答案:

没有答案