behaviorSubject next() 不工作 angular 8

behaviorSubject next() not working angular 8

我有一个显示 header 的 HeaderComponent,其中我有一个搜索栏,当用户输入内容并按下回车键时,我会将用户带到 SearchComponent

我想实现这样的功能,即当用户在搜索页面 (SearchComponent) 上时,header 中的 searchBar 不应该可见,而在所有其他页面上应该可见。

为此,我在 HeaderComponent.ts 中添加了变量 searchShow 并在 HeaderComponent.html 中添加了 ng-if, 我 show/hide 搜索栏。

为了改变 searchShow 的值,我实现了 Header.service.ts.

header.service.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class HeaderService {
  showSearch = new BehaviorSubject<boolean>(true);
  public showSearchObservable = this.showSearch.asObservable()
  constructor(){}
}

header.component.ts

import { Component, OnInit } from '@angular/core';
import { HeaderService } from './header.service';
@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
  searchShow;
  constructor(
    private headerService: HeaderService
  ) {}

  ngOnInit() {
    this.headerService.showSearchObservable.subscribe(
      value => {
        this.searchShow = value
        console.log(value) ##==> prints true first time when header is initialized but does not prints anything when search component is loaded
      }
    )
  }
}

search.component.ts

import { Component, OnInit } from '@angular/core';
import { HeaderService } from 'src/app/shared/header/header.service.js';
@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.scss']
})
export class SearchComponent implements OnInit {
 constructor(
    private headerService: HeaderService
  ) {}

  ngOnInit() {
    console.log(this.headerService.showSearch.value) ##==> prints true
    this.headerService.showSearch.next(false)
    console.log(this.headerService.showSearch.value) ##==> prints false, but this value is not emitted to header component
}
}

我错过了什么?请帮忙。谢谢

在search.component.ts你引用

import { HeaderService } from 'src/app/shared/header/header.service.js';

这导致了第二个 headerService 实例。采用 .js 后缀应该可以解决此问题。