cnak2
cnak2

Reputation: 1841

Is there any reason to define observable in constructor if it is initialized as <Observable>

I'm reviewing a block of code and am a little confused as to why the developer implemented things this way. In the class, they initialize two variables at the top of the class. Then then repeat it in the constructor.

Here is relevant imports:

import {Subject, Observable} from 'rxjs';

Here is the code:

  subject: Subject<Boolean>; // Observable Boolean sources
  subject$: Observable<Boolean>;  // Observable Boolean streams

  private _menuWidth: number = 300; // Default menu width

  constructor() {
    this.subject = new Subject<Boolean>();
    this.subject$ = this.subject.asObservable();

  }

I don't have access to the developer, so wondering is this makes sense to anyone.

I'm new to Angular and may be missing something.

Upvotes: 0

Views: 76

Answers (1)

Martin Nuc
Martin Nuc

Reputation: 5764

At the top of the class they didn't initialize those properties. They just defined there are such properties of given type. But there is nothing executed.

Typescript during compilation basically strips types. So it will actually looks like this:

_menuWidth = 300; // Default menu width

constructor() {
   this.subject = new Subject<Boolean>();
   this.subject$ = this.subject.asObservable();
}

The constructor of Subject for example is executed only in constructor. Not when saying that variable is of type Subject.

Upvotes: 1

Related Questions