Dev Govindji
Dev Govindji

Reputation: 23

TypeScript Observable Error While Trying to Make Multiple Requests to an API (Angular, TypeScript, RxJS)

I am getting this error:

ERROR in src/app/fetch-trefle.service.ts:86:31 - error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value.

86         mergeMap((item: any): Observable<any> => {

Here is my code in my service:

import { Injectable } from '@angular/core'
import { HttpClient } from '@angular/common/http'
import { Observable } from 'rxjs'
import { pluck, concatMap, mergeMap, map, filter, first, elementAt } from 'rxjs/operators'
import { of } from 'rxjs'

interface GrowthData {
  id: number
  common_name: string
  scientific_name: string
  growth: {
    minimum_precipitation: {
      mm: number
    }
    maximum_precipitation: {
      mm: number
    }
  }
}

@Injectable({
  providedIn: 'root'
})
export class FetchTrefleService {

  constructor(private http: HttpClient) { }
  plantId = 273225

  url = `https://trefle.io/api/v1/plants?token=${this.token}`
  growthUrl = `https://trefle.io/api/v1/plants/${this.plantId}?token=GTF4gOKNDJTmYmR2ut6r6y1fyD3pN1GrGSEoST_s0mA`

  proxyurl = 'https://cors-anywhere.herokuapp.com/'

  page = '&page=1'

  id
  common_name
  scientific_name
  growth: {
    minimum_precipitation: {
      mm
    }
    maximum_precipitation: {
      mm
    }
  }


  fetchAllPlantData(): Observable<any> {
    return this.getPlantGrowth()
    return this.getPlantImageIdName()
  }

  getPlantImageIdName(): Observable<any> {
    return this.http.get(this.proxyurl + this.url + this.page)
      .pipe(
        pluck("data"),
      )
  }

  getPlantGrowth(): Observable<any> {
    return this.http.get(this.proxyurl + this.growthUrl + this.page)
      .pipe(
        pluck("data"),
        pluck("main_species"),
        mergeMap((item: any): Observable<any> => {
          this.id = of(item["id"]),
            this.common_name = of(item["scientific_name"]),
            this.scientific_name = of(item["scientific_name"]),
            this.scientific_name = of(item["scientific_name"]),
            this.growth.minimum_precipitation.mm = of(item["growth"]["minimum_precipitation"]["mm"]),
            this.growth.maximum_precipitation.mm = of(item["growth"]["maximum_precipitation"]["mm"])
        })
      )
  }
}

Here is my code in the component:

import { Component } from '@angular/core'


import { FetchTrefleService } from './fetch-trefle.service'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  plants: any

  constructor(private fetchTrefleService: FetchTrefleService) { }

  getAllPlants() {
    this.fetchTrefleService.fetchAllPlantData().subscribe(res => {
      console.log(res)
      this.plants = res
    })
  }
}

I am trying to make two requests to the Trefle API and collect multiple values from each JSON response. It was working fine when I was doing single requests when I refactored to do multiple requests it gave the TS error at the top. I am assuming the issue deals with syntax or something I don't know about the behavior or Observables and RxJS.

Thank you!

Upvotes: 1

Views: 191

Answers (2)

Mukesh Ranjan
Mukesh Ranjan

Reputation: 165

You need to return observable from merge map body.

const click$ = fromEvent(document, 'click');

  click$
        .pipe(
                  mergeMap((e: MouseEvent) => {
                              return of({
                                        x: e.clientX,
                                        y: e.clientY,
                                        timestamp: Date.now()
                       });
                 })
             )

Upvotes: 2

brightpants
brightpants

Reputation: 525

Your mergeMap block need a return that returns an observable.

Editing because I wrongly pressed send

I guess what you need is just a tap or a do. mergeMap expects to receive an Observable to continue the flow.

Substitute your mergeMap for this:

    tap((item: any) => 
          this.id = item.id
          ...
        )

Upvotes: 0

Related Questions