私はAngular2でアプリを持っています。どこにナビゲーションリンクなどを含むトップレベルコンポーネントがあります。そして、ルータのアウトレットはこれの中に入れ子になっています。これらのネストされたページの1つに、トップレベルのコポネントの変更を反映させるアクションが必要です。Angular2観測可能なサービスはコンポーネント間で動作しているようです。
ObservableサービスをAngular2で実装しようとしました。同じコンポーネント内で動作します。しかし、私はObservableを根底から購読しようとします。私は何のイベントも得ていない。
私のサービスは、次のようになります。
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class Announcer {
// Observable sources
private cartTotalSource = new Subject<number>();
private wishlistTotalSource = new Subject<number>();
// Observable sources
cartTotalAnnounced$ = this.cartTotalSource.asObservable();
wishlistTotalAnnounced$ = this.wishlistTotalSource.asObservable();
// Service message commands
announceCartChange(value: number) {
this.cartTotalSource.next(value);
}
announceWishlistChange(value: number) {
this.wishlistTotalSource.next(value);
}
}
私はそれが動作するコンポーネントのコンテキストでそれを使用すると、私が発表する、と同じファイル内の更新を購読することができます。
ngOnInit(){
this.announcer.cartTotalAnnounced$.subscribe(total => {
this.cartTotal = total;
});
this.announcer.wishlistTotalAnnounced$.subscribe(total => {
this.wishlistTotal = total;
});
}
getCartAndWishlistTotal() {
this.cartService.getCartTotal(CartType.Cart, "")
.subscribe(total => {
this.announcer.announceCartChange(total);
});
this.cartService.getCartTotal(CartType.Wishlist, "")
.subscribe(total => {
this.announcer.announceWishlistChange(total);
});
}
しかし、いつ私のトップレベルのコンポーネント(上記のスニペットのngOnInit()とまったく同じコードを使用しています)。加入者は決して発砲しない。
誰かが私が間違っている方向に私を指摘できますか?
サービスをrootのプロバイダに登録しますか? –