0

this is my class ts code

this.product$ = <BehaviorSubject<Product>>this.route.params.switchMap(
  (params): BehaviorSubject<Product> =>
   this.productService.getProduct(params['_id'])
);

this is code from service

  getProduct(_id: string): BehaviorSubject<Product> {
    const bs = new BehaviorSubject<Product>
                   (ProductService.initializeProduct());
    if (_id !== '0') {
      this.productSub = this.databaseService.getProduct(_id).subscribe(
        product => {
        bs.next(product);
        }
      );
    }
    return bs;
  }

I declare type, and also cast type, but yet when I write

console.log(product$.getValue)

I get this error:

ERROR TypeError: this.product$.getValue is not a function

thanks

cartant
  • 57,105
  • 17
  • 163
  • 197
Aladdin Mhemed
  • 3,817
  • 9
  • 41
  • 56

1 Answers1

3

That isn't how switchMap - and RxJS, in general - works. The observable returned by an operator depends upon the observable upon which the operator is called. Said observable can implement lift to return an observable instance of the same type.

The result of your call to switchMap will be lifted from the this.route.params observable. It's not a BehaviorSubject and does not have a getValue method.

cartant
  • 57,105
  • 17
  • 163
  • 197
  • You can't do what you appear to want to do in the snippet. And the code in your question is all there is to go on. Extrapolating from the code, it looks like you are attempting access something synchronously and that is not possible. – cartant Jul 14 '17 at 05:18
  • that's correct, I'm trying to get value synchronously, and this is possible with BehaviorSubject, my only problem is that I couldn't return BehavorSubject from swichmap. I want to escape the nested code in subscribe and enjoy the elegance of switchmap. – Aladdin Mhemed Jul 14 '17 at 05:20
  • It's not possible because the `this.route.params` observable and the observable returned by `this.databaseService.getProduct` are almost certainly not synchronous. You will have to deal with the asynchronicity. – cartant Jul 14 '17 at 05:23