Angular 2 + RxJS BehaviorSubject订阅调用无效

时间:2016-09-24 21:53:23

标签: angular rxjs

我正在尝试构建一个简单的头部组件,到目前为止只是尝试使用NavService内部的BehaviorSubject上的subscribe方法打印在其中注册的Navigation的id。 NavService注册Nav并在BehaviorSubject上调用下一个方法。但该值不会传输到标头组件。我得到的只是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

1 个答案:

答案 0 :(得分:2)

您的指令声明不正确,并且未在您的模块中声明。

更改您的NavDirective
@Component({
  selector: '[custom-nav-1]',
})

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

然后通过

在您的应用模块中声明它
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.