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

时间:2018-02-20 09:58:03

标签: angular typescript observable

我正在使用观察者订阅服务。这是我的InterfaceService:

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class InterfaceService {
  private contentFlag = new Subject();

  public getContent(): any {
    return this.contentFlag;
  }

  public change(): void {    
    this.contentFlag.next(true);  
  }
}

这是我的组件:

import { Component, OnInit } from '@angular/core';
import { InterfaceService } from '../../-services/interface.service';

@Component({
  selector: 'app-main-content',
  template: `<div *ngIf="showContent"> My Content </div>`  // why it is always hidden ?
})

export class MainContentComponent implements OnInit {
  private content$: any;
  public showContent = false;

  constructor(private interfaceService: InterfaceService) {}

  ngOnInit() {
    this.content$ = this.interfaceService.getContent();

    this.content$.subscribe(function(data) {
      this.showContent = data;      
      console.log('Here comes true:', data); // it works - here shows true
    });
  }
}

当其他组件生成interfaceService.change()时,我在控制台中得到'true'。

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

我做错了什么?我应该刷新订阅模板吗?怎么样?或者架构有问题吗?

2 个答案:

答案 0 :(得分:1)

尝试使用ngAfterViewInit()代替ngOnInit()

ngAfterViewInit() {
this.content$ = this.interfaceService.getContent();

this.content$.subscribe(function(data) {
  this.showContent = data;      
  console.log('Here comes true:', data); // it works - here shows true
});
}

答案 1 :(得分:0)

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

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