Angular 2 + RxJS BehaviorSubject subscribe call no

2019-09-13 18:33发布

问题:

I am trying to build a simple header component which as of now just tries to print the id of the Navigation that is registered inside of it using the subscribe method on a BehaviorSubject inside of a NavService. The NavService registers the Nav and calls the next method on the BehaviorSubject. But the value does not transmit to the header component. All I get is the initial value of the BehaviorSubject. Could you please tell me what I am doing incorrectly?

Header Component:

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

Nav Directive:

@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

回答1:

Your directive is being declared incorrectly and it's not being declared in your module.

Change your NavDirective from

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

to

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

and then declare it in your app module by

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 {
}

I also provided your NavService in your AppModule instead of your individual components. You can remove the providers: [NavService] line from all of your components, directives, and pipes in your module because the module is now providing it.

Here's your plunker modified with my changes.



标签: angular rxjs