2

RxJS の新しいバージョン -> "rxjs": "5.0.0-beta.6" を使用する基本的な angular 2 アプリを作成しようとしています。

私はクックブックの指示に従い、アプリのどの部分でもメッセージを表示するために呼び出すことができる通知サービスを作成しようとしました。

私が抱えている問題は.next()、次の通知を追加するために呼び出すと、これがサブスクリプションによって取得されないことです。へのthis.displayMessage(notification);呼び出し後、回線は実行されませんnewNotification。コードに BehaviourSubject 型を追加したところ (チュートリアルで使用された Subject とは対照的に)、初期値がサブスクリプションによって取得されていることがわかりました。これthis.displayMessage(notification);は初期化時に正常に呼び出されました。NotificationServiceこれは、クラスで . next() を呼び出す方法/場所に関係があると思います。

関連するクラスは次のとおりです。

通知サービス:

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

@Injectable()
export class NotificationService {
  // Observable string sources
  private notificationSource = new BehaviorSubject<Notification>(new Notification({message:"test", priority:-1}));
  notifications$ = this.notificationSource.asObservable();

  newNotification(message: string, priority: number) {
    this.notificationSource.next(new Notification({ message, priority }));
  }

}

メッセージコンポーネント:

import { Component, OnDestroy, OnInit } from '@angular/core';

import { Notification } from '../notification/notification';
import { NotificationService } from '../notification.service/notification.service';
import {MdIcon, MdIconRegistry} from '@angular2-material/icon';
import { Subscription }   from 'rxjs/Subscription';

@Component({
  selector: 'message-container',
  styleUrls: ['./app/message/message.component.css'],
  templateUrl: './app/message/message.component.html',
  directives: [MdIcon],
  providers: [NotificationService, MdIconRegistry]

})
export class MessageComponent implements OnDestroy, OnInit {
  notification: Notification;
  subscription: Subscription;
  constructor(
    private notificationService: NotificationService) {
    this.notificationService = notificationService;
  }
  ngOnInit() {
    this.subscription = this.notificationService.notifications$.subscribe(
      notification => {
        this.displayMessage(notification);
      }, err => console.log(err), () => console.log("completed: "));
  }

  displayMessage(notification: Notification) {
    this.notification = notification;
    window.setTimeout(() => { this.notification = null }, 3000);
  }
  ngOnDestroy() {
    // prevent memory leak when component destroyed
    this.subscription.unsubscribe();
  }
}

誰かが試してみるべき他のことについて何かアイデアを持っているなら、それは素晴らしいことです. どうもありがとう

編集:ここの完全なレポ: https://github.com/sandwichsudo/sentry-material/tree/notifications/src/app

4

1 に答える 1

2

NotificationServiceGitHub がリポジトリに見つかりません。

複数回提供しているNotificationServiceため、異なるインスタンスが作成され、あるインスタンスにサブスクライブして別のインスタンスに送信しているという結果になると思います。

のみNotificationServiceまたはのみがあることを確認してください。他のすべてのコンポーネントとディレクティブから削除します。bootstrap(AppComponent, [NotificationService, ...]) providers: [NotificationService]AppComponentproviders: [...]

于 2016-06-15T15:33:06.450 に答える