Encountering TypeScript Observable Error When Sending Multiple API Requests (Angular, TypeScript, RxJS)

Encountering an Issue:

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's the code snippet from 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"])
        })
      )
  }
}

Snippet from 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 facing an issue with making multiple requests to the Trefle API and extracting various data points from each JSON response. The code was functioning correctly when making single requests but after refactoring for multiple requests, I encountered the TypeScript error mentioned above. It seems to be related to syntax or my understanding of Observables and RxJS behavior. Any insights would be greatly appreciated.
Thank you!

Answer №1

In order to properly handle the click event, make sure to return an observable from within the mergeMap block.

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

  clickEvent$
        .pipe(
                  mergeMap((event: MouseEvent) => {
                              return of({
                                        xPosition: event.clientX,
                                        yPosition: event.clientY,
                                        timestamp: Date.now()
                       });
                 })
             )

Answer №2

In order to fix your mergeMap block, you should ensure that it returns an observable.

I am making this edit because I accidentally hit send too soon.

It seems like what you actually need is a tap or a do operator. mergeMap requires an Observable to proceed with the flow.

Try replacing your mergeMap with the following code:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing Angular2 with an external filter in ag-Grid

I am looking to implement external filtering on ag-grid using angular2. After reviewing the ag-grid example on github, it appears that external filters are not implemented and a similar question remains unanswered. Is there a way to incorporate external f ...

Angular: Utilizing Parameters in HTTP GET Requests

I've recently started using Angular. Currently, I'm working on sending a parameter in an HTTP GET request. This is what my code looks like: for (var i = 0, len = this.recentArtists.topartists.artist.length; i < len && i < h ...

Module or its corresponding type declarations not found in the specified location.ts(2307)

After creating my own npm package at https://www.npmjs.com/package/leon-theme?activeTab=code, I proceeded to set up a basic create-react-app project at https://github.com/leongaban/test-project. In the src/index.tsx file of my react app, I attempted to im ...

Turning a WebSocket server into an RXJS API in NodeJs without using Subjects: A step-by-step guide

How can I transform the popular ws module into a reactive api in Node.js effectively? I know that subjects can assist in bridging non-reactive to reactive events, but the issue arises when it comes to disposing of dependent objects. var WebSocketServer ...

syncfusion export pdf demonstrating the toggle button's current state

Currently, I am using syncfusion for converting my page to PDF format. I have a toggle button that is default set to true. However, regardless of the actual state of the toggle button, it always appears as on (true) when exported to PDF. I attempted to s ...

The leaflet popup fails to open for the second time

I used a for loop to create markers on the map. When I click on a marker, a popup opens. However, after clicking on the same marker a second time, the popup does not open. My $scope.resSearchAnnouncement contains JSON data. How can I resolve this issue? ...

Is there a way to programmatically add a timestamp to a form in Angular6?

Is there a way to automatically populate new forms with the current datetime value? this.editForm.patchValue({ id: chatRoom.id, creationDate: chatRoom.creationDate != null ? chatRoom.creationDate.format(DATE_TIME_FORMAT) : null, roo ...

When attempting to deploy my app, I encountered a CORS error with Nest.js

Currently, I am in the process of building a Nest.js - React.js application. However, I am encountering a cors error despite having cors enabled in my main.ts file of Nest.js. While my application functions smoothly on localhost and an IP address in produ ...

Creating a variable within an ngFor loop

For my angular2 project, I need to display a matrix of workers and courses. Here's the current code I am using: <tr *ngFor="let worker of workers"> <td class="{{worker.fired ? 'fired-worker':''}}">{{worker.lastName ...

Utilizing node-canvas to import a .ttf file into TypeScript for registering a custom font

I am trying to incorporate locally stored fonts (in ttf format) into a canvas that is generated using node-canvas. To achieve this, I have created a typings file and included it in my tsconfig: fonts.d.ts declare module '*.ttf'; The fonts hav ...

After the initialization of the app, make sure to provide an InjectionToken that includes the resolved configuration

During the initialization of the application, I am looking to retrieve the configuration using a factory that will be resolved through the APP_INITIALIZER provider. export function loadConfig(): () => Promise<Config> { // return promised confi ...

Transferring Data from Component to Dialog without Two-Way Model Binding

Presently, I am working with a fruits component and an update fruits component. The fruit component displays different chips of fruit along with a button to update those chips. The currently selected fruits are passed in the dialog data. Fruits Component ...

NestJS API experiencing issues connecting to MongoDB due to empty index keys

My goal is to create an API with NestJS using TypeORM. Initially, I had set up the API to work with Postgres, but now I need to migrate it to MongoDB. After making the necessary changes, the connection is established successfully. However, I encounter an ...

Is there a way to reverse the animation playback in Angular?

I am working on an animation that involves a box fading from its original color to yellow. However, I would like to achieve the opposite effect: when the page loads, I want the box to start off as yellow and then fade back to its original color. The challe ...

Setting up a custom PrimeNG theme to match our unique style is a great way to

I am currently using the most recent version of "primeng": "^12.2.0", and I am looking to implement my own custom theme for primeng. Despite searching through numerous blogs, I have yet to find a solution. In an attempt to create my cu ...

Is there a specific type in typescript that represents every iterable object?

We have a unique function shown below: export const transformUndefinedToNull = (obj) => { const convert = (o) => { Object.keys(o).forEach((key) => { const value = o[key]; if (value === undefined) { o[key] = null; } ...

Getting a list of the stack resources available in cloudformation using TypeScript

My team is developing an application that will deploy multiple stacks to AWS. One of these stacks is called SuperStar, and it can only exist once per AWS account. I am currently exploring how our TypeScript CDK can retrieve a list of stacks from CloudFor ...

Encountering TS2339 error while attempting to append a child FormGroup within Angular framework

I'm currently working with Angular8 and facing an issue while attempting to include a child FormGroup to a form using the addControl method: this.testForm = new FormGroup({ id: new FormControl(0), people: new FormGroup({ } ...

Encountered Angular 7 Error: Unable to access pro due to TypeError

I've encountered an error in my Angular front-end application: https://i.sstatic.net/koqvm.png Error: index.js:3757 TypeError: Cannot read pro Here's what I have tried so far: I inspected the code but couldn't find the root cause of t ...

Iterate endlessly over CSS styles in Angular 4

I'm looking to create a website background 'screensaver' by looping through an array of background URLs with a delay between switches. Currently, I have the array stored in my .ts file and I am using the NgFor directive in my HTML. However, ...