2016-09-24 23 views
0

私は今のところ、内部のBehaviorSubjectのsubscribeメソッドを使ってその内部に登録されているNavigationのIDを表示しようとする単純なヘッダーコンポーネントを構築しようとしています。 NavService。 NavServiceはNavを登録し、BehaviorSubjectの次のメソッドを呼び出します。しかし、値はヘッダーコンポーネントに送信されません。私が得るのは、BehaviorSubjectの初期値だけです。私が間違ってやっていることを教えてください。Angular 2 + RxJS BehaviorSubject subscribe call not working

ヘッダーコンポーネント:

@Component({ 
    selector: 'my-custom-header', 

    template: ` 
    <div class="container"> 
     This is a header 
     <nav custom-nav-1>Custom Nav 1</nav> 
     <ng-content></ng-content> 
     <div>Number of Nav Registered: {{noOfNav}}</div> 
    </div> 
    `, 
    styles: ['.container { border: 1px solid; }'], 
    providers: [NavService] 
}) 
export class HeaderComponent { 
    title = 'Hello!'; 
    noOfNav = 0; 

    constructor(private navService: NavService) {} 

    ngOnInit() { 
    this.navService._navSubject.subscribe({ 
     next: (id) => { 
     this.noOfNav = id; 
     } 
    }); 
    } 
} 

NavService:

@Injectable() 
export class NavService { 
    public _navSubject: BehaviodSubject = new BehaviorSubject<number>(0); 

    registerNavId(id: number) { 
    this._navSubject.next(id); 
    } 
} 

ナビ指令:

@Component({ 
    selector: '[custom-nav-1]', 
    providers: [NavService] 
}) 
export class NavDirective { 
    constructor(private navService: NavService) {} 

    ngOnInit() { 
    this.navService.registerNavId(1); 
    } 
} 

Plunk:https://plnkr.co/edit/0XEg4rZqrL5RBll3IlPL?p=preview

答えて

2

あなたのディレクティブは、私と宣言されていますncorrectly、あなたのモジュールで宣言されていません。

@Directive({ 
    selector: '[custom-nav-1]', 
}) 

@Component({ 
    selector: '[custom-nav-1]', 
}) 

からあなたNavDirectiveを変更し

、その後

import { NavDirective } from './nav.directive'; // you didn't have this before 
import { NavService } from './nav.service'; // or this 
// other imports here 

@NgModule({ 
    imports: [ 
    BrowserModule, 
    FormsModule, 
    HttpModule 
    ], 
    declarations: [ 
    AppComponent, 
    HeaderComponent, 
    NavDirective // important! 
    ], 
    providers: [NavService], // also important! 
    bootstrap: [ AppComponent ] 
}) 
export class AppModule { 
} 

によってアプリのモジュールで宣言私はまた、代わりにあなたのあなたのAppModuleであなたのNavServiceを提供しました個々のコンポーネント。モジュールが現在提供しているので、モジュール内のすべてのコンポーネント、ディレクティブ、およびパイプからproviders: [NavService]行を削除できます。

Here's your plunker modified with my changes.

+0

ありがとうございます!これは機能します。 – takeradi

+0

私は助けることができる嬉しい:) –