How can I return Observable of IEmployees with productName from allProducts$ in RXJS?

Discussion in 'JavaScript' started by asifakhtar, Jun 21, 2022.

  1. #1
    I want to return Observable from GetEmployeeByID function that has a matching productName from allProducts$:

    allProducts$ = this.state$.pipe(
    map(x => x.allProducts as IProducts[] || [] as IProducts[]),
    distinctUntilChanged());
    
    GetEmployeeByID(Id: number): Observable<IEmployees> {
    return this.allEmployees$.pipe(
    map(res => <IEmployees>res.find(data => data.id === Id) ?? { id: -1, name: "N/A", email: "N/A", gender: "N/A", productid: -1, productName: "N/A" } as IEmployees),
    switchMap((Employee: IEmployees) => {
    return this.allProducts$.subscribe(allProducts => {
    return of({
    ...Employee,
    productName: allProducts.find(Product => Product.productid == Employee.productid)?.name
    }) as IEmployees
    })
    })
    )
    }
    Code (javascript):
     
    Last edited by a moderator: Jun 23, 2022
    asifakhtar, Jun 21, 2022 IP