Hattori
Hattori

Reputation: 63

angular2 - Not able to get data from subject

I want to get initialise and get data from service using a subject. What am I doing wrong?

HomeComponentComponent.TS

export class HomeComponentComponent implements OnInit {

  public homeSub;
  constructor(
    private subService: SubjectService
  ) { }
  
  ngOnInit() {
    this.subService.initialiseSubject(true);
    this.subService.getSubject().subscribe(res => {
      this.homeSub = res;
      console.log(res);
    })
  }

}

HomeComponentComponent.HTML

<p>
{{homeSub}}
</p>

subject.service.ts

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

@Injectable({
  providedIn: 'root',
})
export class SubjectService {

  constructor() { }
  private subTest = new Subject<boolean>();

  initialiseSubject(params: boolean) {
    this.subTest.next(params);
  }
  getSubject() {
    return this.subTest.asObservable();
  }
}

I am not getting any output on console or html.
Stackblitz link

Upvotes: 1

Views: 294

Answers (1)

Kunal Karmakar
Kunal Karmakar

Reputation: 591

If you change to BehaviorSubject, you will get the emitted value.

private subTest = new BehaviorSubject<boolean>(false);

Please review this post.

Upvotes: 2

Related Questions