【问题标题】:Subscribe function is not trigger when I call function next on BehaviourSubject当我在 BehaviorSubject 中调用下一个函数时,订阅函数不会触发
【发布时间】:2020-03-21 22:24:56
【问题描述】:

我有 2 个组件和 2 个组件之间共享的一项服务,比如说 ComponentA 和 ComponentB。应用程序工具栏的一个组件(Comp. A)和另一个组件 B 使用路由模块进行路由。这是 HTML:

<a></a>
<router-outlet></router-outlet>

之所以这样,是因为我希望工具栏始终存在,固定在顶部。 在组件 A 的 HTML 中,我可以选择应用程序的语言。在组件 BI 中有一些来自后端的内容,具体取决于所选语言。我希望当用户更改语言时,内容来自服务器,进行渲染。我正在使用该服务调用后端并渲染新内容.我的问题来了,对服务器的调用已完成并且没问题,但它从未进入订阅功能。我尝试使用共享模块(有或没有 forRoot()),我试图使服务成为模块的提供者,并将模块(AppRoutingModule)导入另一个模块(AppModule)。在这一刻,我达到了“没有服务提供者!”的地步。控制台中的错误。服务和组件的代码: 服务:

@Injectable()
export class SharedService extends GlobalHttpService<HomeSection> {
  private sectionsSubject: BehaviorSubject<HomeSection[]>;
  constructor(private http: HttpClient) {
    super("api/path", new GlobalSerializer(HomeSection), http);
    this.sectionsSubject = new BehaviorSubject<HomeSection[]>([]);
  }

  load() {
    this.list().subscribe(res => {
      this.sectionsSubject.next(res);
    });
  }
  get content() {
    return this.sectionsSubject.asObservable();
  }
}

AppModule

@NgModule({
 imports:[AppRoutingModule]
})
export class AppModule {}

AppRoutingModule

export function SharedServiceFactory(http: HttpClient){
  return new SharedServiceFactory(http);
}

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: [
    {
      provide: SectionService,
      useFactory: SectionServiceFactory,
      deps: [HttpClient]
    }
  ]
})
export class AppRoutingModule {}

组件A:

@Component({
  selector: "a",
  templateUrl: ".a.component.html",
  styleUrls: ["./a.component.scss"]
})
export class AComponent implements OnInit {
  constructor(
    public authentificationService: AuthenticationService,
    private languagesService: LanguagesService,
    private sharedService: SharedService
  ) {
  }
 ngOnInit() {
//other logic;
}

updateLanguage(event) {
// other logic;
this.sharedService.load();
}

组件B

@Component({
  selector: "app-b",
  templateUrl: "./b.component.html",
  styleUrls: ["./b.component.scss"]
})
export class BComponent implements OnInit {
  constructor(
    private sharedService: SharedService,
  ) {}

ngOnInit() {
 this.sharedService.load();
 this.sharedService.content.subscribe(s => {
 // logic
 });
}

我怎样才能拥有一个 SharedService 实例,或者我可以在另一个模块中包含一个模块?

【问题讨论】:

    标签: angular angular8 angular-services angular-module


    【解决方案1】:

    尝试在您的服务中执行此操作:

    @Injectable({ providedIn: 'root' })
    

    并从 AppRoutingModule 中删除该服务的提供。 如果您使用providedIn: 'root',则无需在其他地方提供。它将在 Angular 树的最顶部注入服务,因此您将始终拥有相同的实例。它的另一个好处 - 它使服务可以摇树。

    【讨论】:

      【解决方案2】:

      首先在 AppModule 中导入服务:

      AppModule

      @NgModule({
       imports:[AppRoutingModule],
       providers: [SharedService]
      })
      export class AppModule {}
      

      或:

      @Injectable({ providedIn: 'root' }) 导出类 SharedService 扩展 GlobalHttpService { ... }

      然后,您不必在 SharedService 中创建方法来返回 Observable 事件,您只需在构造函数中创建一次属性和实例即可。

      共享服务

      @Injectable()
      export class SharedService extends GlobalHttpService<HomeSection> {
        private sectionsSubject: BehaviorSubject<HomeSection[]>;
        public content$: Observable<HomeSection[]>;
        constructor(private http: HttpClient) {
          super("api/path", new GlobalSerializer(HomeSection), http);
          this.sectionsSubject = new BehaviorSubject<HomeSection[]>([]);
          this.content$ = this.sectionsSubject.asObservable();
        }
      
        load() {
          this.list().subscribe(res => {
            this.sectionsSubject.next(res);
          });
        }
      }
      

      终于在你的组件 B 中:

      @Component({
        selector: "app-b",
        templateUrl: "./b.component.html",
        styleUrls: ["./b.component.scss"]
      })
      export class BComponent implements OnInit {
        constructor(
          private sharedService: SharedService,
        ) {}
      
      ngOnInit() {
       this.sharedService.load();
       this.sharedService.content$.subscribe(s => {
           // logic
       });
      }
      

      【讨论】:

        猜你喜欢
        • 2018-06-05
        • 1970-01-01
        • 2020-03-15
        • 2020-01-06
        • 1970-01-01
        • 2018-10-26
        • 1970-01-01
        • 1970-01-01
        • 2017-09-30
        相关资源
        最近更新 更多