Acquiring a collection of objects retrieved from a set of URLs using rxjs and typescript

I have an item to work with:

let DataObject = { 
  'item1' : './someitem1.json',
  'item2' : './someitem2.json',..
};

I want to fetch all items using RxJS and notify the subscriber only after all items have been fetched. Additionally, I want the subscriber to receive a result object with the original keys. For example:

let result = { 
  'item1' : fetchedData1,
  'item2' : fetchedData2,..
}

The code snippet that I currently have is as follows:

import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/forkJoin';
import 'rxjs/add/operator/concatAll'; 
import 'rxjs/add/observable/of';

let observableBatch = [];
for (let key in DataObject) {
    observableBatch.push(
      this.http.get(DataObject[key]).map(
         (res) => {
             return Observable.of({[key] : res.json()})
         }
      )
    )
}
let mergedObs =Observable.forkJoin(observableBatch).concatAll();
mergedObs.subscribe((res) => {
    console.log(res);
});

However, I am encountering an error stating "Property 'subscribe' does not exist on type '{}[]'."

How can I resolve this error? Is there a more concise way to achieve the same functionality?

Answer №1

One great feature of using forkJoin is that you do not have to utilize concatAll. With forkJoin, it subscribes to all source Observables and waits until each one completes before emitting values, rather than Observables.

If you want to avoid creating an array of Observables beforehand or if the list of URLs is dynamic, you can implement a solution like this:

let UrlObject = {
    'url1' : './someurl1.json',
    'url2' : './someurl2.json',
    'url3' : './someurl3.json',
    'url4' : './someurl4.json',
    'url5' : './someurl5.json',
};

function httpRequest(key, url) {
    return Observable.of(url)
        .delay(1000)
        .map(response => [key, response.split('').reverse().join('')]);
}

Observable.from(Object.keys(UrlObject).map(key => [key, UrlObject[key]]))
    .flatMap(arr => httpRequest(arr[0], arr[1]))
    .toArray()
    .map(arr => {
        const obj = {};
        arr.forEach(respArr => obj[respArr[0]] = respArr[1]);
        return obj;
    })
    .subscribe(console.log);

The output to console would be:

{ url1: 'nosj.1lruemos/.',
  url2: 'nosj.2lruemos/.',
  url3: 'nosj.3lruemos/.',
  url4: 'nosj.4lruemos/.',
  url5: 'nosj.5lruemos/.' }

Take a look at the live demo here: https://jsbin.com/hozumix/2/edit?js,console

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

What is the reason behind VS Code not showing an error when executing the command line tsc shows an error message?

Deliberately introducing a typo in my code results in an error. Here is the corrected code: declare const State: TwineState; If I remove the last character and then run tsc on the command line, it throws this error: tsc/prod.spec.ts:7:22 - error TS2304: ...

A step-by-step guide on generating a TypeScript class using JSON data

Working with Angular and making a call to an external API. The JSON data is structured as follows: [ { "AccessGroupsIdList": [], "FirstName": "Greg", "LastName": "Tipton", ...

Chaining switchMaps(s) consecutively

I am currently in the process of developing an editor that will allow users to select 1 account from a list of accounts, also known as a Chart of Accounts (COA). The author will have the ability to specify the type/subtype that should be selected, and the ...

Code coverage analysis in a node.js TypeScript project consistently shows no coverage metrics

I'm currently working on a backend TypeScript project where I'm aiming to obtain coverage reports for unit test cases. However, Jest is returning empty coverage reports both in the terminal and in the HTML report, with no information provided. Ev ...

What is the best way to call a method within a TypeScript class using its name as a string while already inside the class itself?

Currently, I am developing a class that automates the creation of routes for Express and invokes a function in a controller. However, upon trying to execute this[methodName](req, res), I come across an error message stating: 'Element implicitly has an ...

Can someone please explain how I can extract and display information from a database in separate text boxes using Angular?

Working with two textboxes named AuthorizeRep1Fname and AuthorizeRep1Lname, I am combining them in typescript before storing them as AuthorizeRep1Name in the database. Refer to the image below for the result. This process is used to register and merge the ...

Import resolves Uncaught ReferenceError by preventing access to 'xx' before it is initialized

Currently, I am troubleshooting a peculiar error that has come up. Within my service file where all other services are stored, I have included the import of one component along with all the other services required by the frontend. import { VacationComponen ...

The custom form input in Angular2 is throwing an error because it is trying to access the property 'name' of an

Upon switching to the latest Angular version 2 final, I encountered the following error Uncaught TypeError: Cannot read property 'name' of undefined This is my customized input import { Component, EventEmitter, Provider, forwardRef } from &a ...

Error: Jest + Typescript does not recognize the "describe" function

When setting up Jest with ts-jest, I encountered the error "ReferenceError: describe is not defined" during runtime. Check out this minimal example for more information: https://github.com/PFight/jest-ts-describe-not-defined-problem I'm not sure what ...

How do you go about making a prop optional in Typescript based on a generic type?

In my app, I have a specific type with optional props based on a generic type: type MyCustomType<R extends Record<string, string> | undefined, A extends string[] | undefined> = { record: R, array: A } There is a function that directly uses ...

How do I insert a new column into the result set of a query in Prisma?

Imagine a scenario where there are two tables: User, which has fields for name and Id, and Post, which has fields for name and content. These tables are connected through a many-to-many relationship (meaning one post can have multiple users/authors and eac ...

Exploring the world of mocking tests using Jest and inputs

Is there a way to create a jest test specifically for this function? const input = require('prompt-sync')(); export function choices(): void { const choice = input("Choose a letter"); if (choice === "a") { con ...

Challenge when providing particular strings in Typescript

Something seems to be wrong with the str variable on line number 15. I would have expected the Typescript compiler to understand that str will only ever have the values 'foo' or 'bar' import { useEffect } from 'react' type Ty ...

Jest is having trouble recognizing a custom global function during testing, even though it functions properly outside of testing

In my Express app, I have a custom function called foo that is globally scoped. However, when running Jest test scripts, the function is being recognized as undefined, causing any tests that rely on it to fail. This is declared in index.d.ts: declare glob ...

Having trouble with the service connection in Stackblitz?

Objective: I am trying to establish a connection with the Data service in StackBlitz. Issue: Unfortunately, my attempts are not successful. Can anyone pinpoint what I am overlooking? Project Link: https://stackblitz.com/edit/angular-mpy6pr Many th ...

The assigned type does not match the type 'IntrinsicAttributes & { children?: ReactNode; }'. This property is not assignable

I have been struggling to resolve this issue, but unfortunately, I have not found a successful solution yet. The error message I am encountering is: Type '{ mailData: mailSendProps; }' is causing an issue as it is not compatible with type &apos ...

Error message: Conflicting type declarations across multiple files

I am facing a challenge with my TypeScript 'snippets' project. It seems that multiple .ts files contain type names (like Foo) that are the same. //file-a.ts type Foo = { } //file-b.ts type Foo = { } When attempting to compile, I encounter ...

Having trouble getting the npm package with @emotion/react and vite to function properly

Encountering an issue with the npm package dependencies after publishing, specifically with @emotion/react. This problem arose while using vite for packaging. Upon installing the package in another project, the css property appears as css="[object Ob ...

Guide on invoking child components' functions from the parent component in Angular 6

Main Component import { Component } from '@angular/core'; import { DisplayComponent } from './display.component'; @Component({ selector: 'my-app', template: ` <button (click)="submit()">Call Child Com ...

Node.js has been giving me trouble as I try to install Inquirer

:***Hey Guys I'm Working on a TypeScript/JavaScript Calculator! ...