Home > Software design >  valueChanges event observable not caught in RXJS in angular
valueChanges event observable not caught in RXJS in angular

Time:06-11

In constructor I have:

this.step1FormGroup = this.formBuilder.group({
  firstLastName: new FormControl('')

});

this.step1FormGroup.get('firstLastName').valueChanges.pipe(
  map((a) => {
    console.log('oy!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
    return a;
  })
);

and in template I have this:

<form [formGroup]="step1FormGroup">
  <ng-template matStepLabel>Fill out your name</ng-template>
  <mat-form-field>
    <input matInput
      placeholder='Last name, First name'
      formControlName='firstLastName'>
  </mat-form-field>
  
</form>

but I am not catching the valueChanges, so I am not getting the console.log output. How can I fix this, without using the subscribe() method after the pipe?

CodePudding user response:

The valueChanges function returns an Observable, so it's fine if you are pipeing and doing some operations in there, but in order to actually make it work, somewhere, you need to subscribe to that observable.

Remember, observables by default, are lazy, you don't get the data if you don't subscribe.

this.step1FormGroup.get('firstLastName').valueChanges.pipe(
  map((a) => {
    console.log('oy!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
    return a;
  })
).subscribe(); // here

Also, I recommend moving that logic from your constructor to ngOnInit, that's where all the data initialization should be handled.

  • Related