Home > Back-end >  How can I transfer values from an Observable to an other Observable?
How can I transfer values from an Observable to an other Observable?

Time:01-22

How can achive it that "getObs" Observable have value from subscribe in OnInit method. I need getObs on html template for async pipe.The value (Mydata) what is comming from input decorator is a "Observable(boolean)" type.This is something with pipe and map i think but im not sure.

@Component({
  templateUrl: 'my.html',
  styleUrls: ['my.scss'],
  
})

export class MyClass implements OnInit {
  @Input() data: ; 

  getObs$: Observable<boolean>;

  ngOnInit(): void {
    this.data.myData.subscribe(x=>.....???)
  }
}

CodePudding user response:

That's a standard scenario for using switchMap(), but you use this inside of .pipe() instead of .subscribe().

ngOnInit(): void {
  this.data.myData.pipe(
    switchMap(myDataValue => getObs$.pipe(
      map(getObsValue => {
        // Do something with 'myDataValue' and 'getObsValue'
      )
    )
  ).subscribe();
}

CodePudding user response:

you can do like this:

in your component.ts file:

ngOnInit(): void {
getObs$=this.data.myData;
}

in my.html file:

<p>{{ getObs$ | async }}</p>

CodePudding user response:

I give you an alternative way from the above:

Try by getting your observable from a Behaviour Subject and use .next() to pass a new data:

import { BehaviorSubject, Observable } from 'rxjs';

@Component({
  templateUrl: 'my.html',
  styleUrls: ['my.scss'],
  
})

export class MyClass implements OnInit {
  @Input() data: ; 

  private _getObsBS = new BehaviorSubject<boolean>(false);
  getObs$ = this._getObsBS.asObservable();


  ngOnInit(): void {
    this.data.myData.subscribe( x => _getObsBS.next(x) )
  }
}
  •  Tags:  
  • Related