2016-09-24 66 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

很高兴我能帮忙:) –