如何正确刷新 Angular 中组件的模板?

Гри*_*чев 5 observable typescript angular

I\xe2\x80\x99m 使用带有观察者订阅的服务。这是我的接口服务:

\n\n
import { Injectable } from \'@angular/core\';\nimport { Subject } from \'rxjs/Subject\';\n\n@Injectable()\nexport class InterfaceService {\n  private contentFlag = new Subject();\n\n  public getContent(): any {\n    return this.contentFlag;\n  }\n\n  public change(): void {    \n    this.contentFlag.next(true);  \n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是我的组件:

\n\n
import { Component, OnInit } from \'@angular/core\';\nimport { InterfaceService } from \'../../-services/interface.service\';\n\n@Component({\n  selector: \'app-main-content\',\n  template: `<div *ngIf="showContent"> My Content </div>`  // why it is always hidden ?\n})\n\nexport class MainContentComponent implements OnInit {\n  private content$: any;\n  public showContent = false;\n\n  constructor(private interfaceService: InterfaceService) {}\n\n  ngOnInit() {\n    this.content$ = this.interfaceService.getContent();\n\n    this.content$.subscribe(function(data) {\n      this.showContent = data;      \n      console.log(\'Here comes true:\', data); // it works - here shows true\n    });\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

当其他组件进行 interfaceService.change() 时,我在控制台中得到 \xe2\x80\x98true\xe2\x80\x99 。

\n\n

但组件模板中没有任何反应。<div *ngIf="showContent"> My Content </div>总是隐藏的。

\n\n

我究竟做错了什么?我应该刷新订阅中的模板吗?如何?还是架构有问题?

\n

AJT*_*T82 1

问题是你正在失去 的范围this。使用箭头函数来维护范围:

this.content$.subscribe((data) => { // here!
  this.showContent = data;      
  console.log('Here comes true:', data); // it works - here shows true
});
Run Code Online (Sandbox Code Playgroud)