2016-09-24 80 views
0

我正在嘗試構建一個簡單的頭文件組件,它現在只是試圖打印在其內部使用Subscriber方法註冊的導航的ID NavService。 NavService註冊Nav並調用BehaviorSubject上的下一個方法。但是該值不會傳輸到標題組件。我得到的只是BehaviorSubject的初始值。你能告訴我我做錯了嗎?Angular 2 + RxJS BehaviorSubject訂閱調用不工作

標題組件:

@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); 
    } 
} 

普拉克:https://plnkr.co/edit/0XEg4rZqrL5RBll3IlPL?p=preview

回答

2

你的指令被宣告我不正確,它不在你的模塊中聲明。

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

@Directive({ 
    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 { 
} 

聲明它你的應用程序模塊在我公司還提供您NavService在你的AppModule,而不是你的個別組件。您可以從模塊中的所有組件,指令和管道中刪除providers: [NavService]行,因爲模塊現在提供它。

Here's your plunker modified with my changes.

+0

非常感謝!這工作。 – takeradi

+0

很高興我能幫忙:) –