1
votes

I made a BehaviourSubject inside a service in angular:

@Injectable()
export class UsuarioService {
  private _altaUsuarioData: BehaviorSubject<AltaUsuarioProvMunModel>;

  constructor(private http: HttpClient) {
    this._altaUsuarioData = new BehaviorSubject(new AltaUsuarioProvMunModel());
  }

  getAltaUsuarioData() {
     return this._altaUsuarioData.asObservable();
 }

I'm accesing it in another component:

  this.datosAltaUsuario: Observable<AltaUsuarioProvMunModel>;

  constructor(){
  this.datosAltaUsuario = this.usuarioService.getAltaUsuarioData();
    this.datosAltaUsuario.subscribe(
      resp => {
            ...
  • How can I unsubscribe from the BehaviourSubject?.
  • Does onDestroy takes care of it?.
  • Am I doing good creating the instance with asObservable() and creating the observable "this.datosAltaUsuario: Observable;"?
  • I'm a bit worried about possible memory leaks

Thank you in advance

1

1 Answers

0
votes
  1. this['subscription'] = this.datosAltaUsuario.subscribe();, then this['subscription'].unsubscribe();
  2. You can do it in ngOnDestroy, but it doesn't do it implicitly : you have to write the unsbuscribe.
  3. I don't know about the best practice, but it's definitely not the worst practice.
  4. If you unsubscribe you don't have to worry.