How to correctly refresh template of component in Angular?

I’m using service with observer subscribing. Here is my 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);  
  }
}

Here is my Component:

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

When other component makes interfaceService.change(), I get ‘true’ in console.

But there is no reaction in Component template. <div *ngIf="showContent"> My Content </div> is always hidden.

What am I doing wrong? Should I refresh template in subscription? How? Or is there a problem with architecture?

Upvotes: 5

Views: 8147

Answers (2)

AVJT82
AVJT82

Reputation: 73357

The problem is that you are losing the scope of this. Use arrow functions to maintain the scope:

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

Upvotes: 1

Try with ngAfterViewInit() instead of 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
});
}

Upvotes: 1

Related Questions