1

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

Hattori
  • 63
  • 1
  • 7
  • 1
    Subjects are "Hot Observables". They emit values regardless of subscribers. You could use a `BehaviorSubject` or a `ReplaySubject`. These specialized subjects propagate values to subscribers who subscribe after the value has been emitted by the subject. – Aluan Haddad Oct 05 '20 at 03:45
  • Thanks, it worked, I changed `Subject` to `BehaviorSubject` – Hattori Oct 05 '20 at 04:17

1 Answers1

2

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

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

Please review this post.

Kunal Karmakar
  • 573
  • 7
  • 12
  • thanks a lot, it worked. I got just one issue with this. Do I have to initialise `BehaviorSubject` always? – Hattori Oct 05 '20 at 05:46
  • 2
    As far as I know, the purpose of using `BehaviorSubject` is to have an initial value. I don't think you can create a `BehaviorSubject` object without any initial value. – Kunal Karmakar Oct 05 '20 at 05:49
  • If you don't want an initial value, you can use a `ReplaySubject` with a retention of `1`. I.e. `new ReplaySubject(1)` – Aluan Haddad Oct 05 '20 at 07:59