Tips for modifying an observable

Previously, I utilized Firebase as my database service. When I received the Observable from Firebase and subscribed to it:

const projectsFromDatabase = this.afDB.list(this.basePath, {
    query: query
});
console.log(projectsFromDatabase.subscribe(res => {console.log(res)}); // just for testing
return projectsFromDatabase;

I obtained the following data structure:

[
 {
   0:
     {data: 0, value : 0, $key: ABC}
 },
 {
   1: 
     {data:1, value:1 , $key: DEF}
 }
] 

Now, I am transitioning from Firebase to MongoDB. I have an observable retrieved from an API:

const projectsFromDatabase = this
      .http
      .get(url)
      .map(res => {
        return res;
      });
    console.log(projectsFromDatabase.subscribe(res => {console.log(res)}); // just for testing
return projectsFromDatabase;

and the data structure is quite different:

[
 {
   0:
    {  
       ABC:{data: 0, value : 0},
       DEF:{data: 1, value : 1}
    }

 }
] 

Is there a way to transform the second observable into something similar to the first one, so that I can subscribe to it later and achieve the same result? I've attempted to subscribe, modify, and push it to a new observable, but the length of my observable always remains at 0. Any other suggestions?

Answer №1

Take a look at this

To achieve your goal, utilize the .map function, much like you would with an http call.

In the example below, I have demonstrated adding a new property to the response object received from the server. Similarly, you can adjust the server response before displaying it on the UI. To provide a practical demonstration, I employed a live API in my example. This should give you a better understanding of how to implement it:

import { Injectable } from "@angular/core";
import { Observable,BehaviorSubject } from "rxjs";
import { HttpClient } from "@angular/common/http";
import { map, filter, catchError, mergeMap } from 'rxjs/operators';

@Injectable()

export class DecoratorService {

constructor(private http: HttpClient){}
  getData(): Observable<any>{

  return this.http.get('https://api.github.com/users/seeschweiler')
     .pipe(map(d => this.modify(d)));
  }

  modify(data){
    data['myOwnProperty'] = "Hey There, I am added by decorator !!"
    return data;
  }

}

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

ngx-scroll-event activated, yet remains elusive

After updating my project from Angular 7 to 8 smoothly, I proceeded with the update to Angular 9. Suddenly, the project was unable to find the required [email protected] package, resulting in a "module not found" error: Cannot find module 'ngx-sc ...

Testing the branch count of optional chaining in Typescript

I am struggling to grasp the concept of branch coverage, especially when it involves optional chaining in TypeScript. Below is my code snippet: type testingType = { b?: { a?: number }; }; export function example(input: testingType) { return input. ...

Angular 4 encounters a hiccup when a mistake in the XHR request brings a halt to a

In my Angular 4 application, I have implemented an observable that monitors an input field. When it detects a URL being entered, it triggers a service to make an XHR request. Observable.fromEvent(this._elementRef.nativeElement, 'input') .debou ...

Ensure that MatTable displays newly added rows

A snippet of an Angular component I am working on shows how I am creating a table: import {Component, Inject} from '@angular/core'; import {MatTableDataSource} from '@angular/material'; import {ChromeDataService} from "../../../../shar ...

"Exploring the power of index signatures and methods in Typescript

What might be the reason for code producing a ts(2411) error? class Greeter { [key: string]: string | number[]; greeting: string; constructor(message: string) { this.greeting = message; } greet(): string { return "Hel ...

How to determine the champion in a game of tic tac toe with the help of Redux and React in

As a beginner in react and redux, I am currently self-studying the concepts. States in my tic-tac-toe project are managed using redux. My goal is to determine the winner when X or O are aligned on the board. Below is my code: // store.ts import { co ...

What is the method for removing an item from my TypeScript to-do list?

I am fairly new to TypeScript and I'm currently facing some challenges in deleting an item from my to-do list. I could use some guidance on how to go about implementing this feature. I have created a deleteHandler function that needs to be integrated ...

Anticipating the desired data types for Jasmine arguments

Lately, I've been in the process of upgrading my Angular version from 10 to 13 in order to utilize TypeScript 4.6. However, during this upgrade, I made some errors with types in my tests and I'm wondering if others have encountered similar issues ...

I'm having trouble retrieving the last 5 values from Firestore. I've gone through the documentation, but I'm still finding it quite confusing

Whenever the previous button is clicked, I am trying to retrieve the previous 5 values in my current project that utilizes Firestore, recoil, React, and Material UI. Below is the code snippet I developed after referencing various tutorials. Sensor Compone ...

Encountering a problem while installing an Angular 2 npm package from an enterprise registry

We are utilizing an enterprise repository for NPM packages that mirrors the traditional registry "http://registry.npmjs.org/". I am currently attempting to fetch the following packages (listed in package.json) "@angular/common": "2.0.0-rc.4", "@angular/co ...

Employ ion-grid for a layout reminiscent of Duolingo's design

I am exploring the idea of creating a layout similar to Duolingo's interface. I have an array that specifies which buttons should be displayed, and I want them to be organized in pairs, with any odd element centered within the layout. However, I am s ...

Searching is disrupted when the page is refreshed in NextJS

When I refresh the page, router.query.title disappears. I have read that I need to use getServerSideProps, but I'm unsure of what to include in the function. Can anyone provide guidance on how to resolve this issue? Update: I followed Yilmaz's s ...

Convert TypeScript-specific statements into standard JavaScript code

For my nextjs frontend, I want to integrate authentication using a keycloak server. I came across this helpful example on how to implement it. The only issue is that the example is in typescript and I need to adapt it for my javascript application. Being u ...

How to efficiently load a compressed bundle.js file in Angular2 with Webpack?

I recently utilized the Webpack Compression plugin to shrink my bundle.js file and successfully obtained a bundle.js.gz version. However, upon launching the application, I encountered an error: Refused to execute script from 'https://example.com/js/ ...

Unexpected error encountered with the release of Angular 2: "Module import of 'ElementRef' resulted in an unexpected value"

After upgrading to Angular 2, I encountered an error related to ElementRef. Initially, I received the error message Angular2 RC5 error:zone.js: Unhandled Promise rejection: No provider for ElementRef which was discussed on this thread. I adjusted my code a ...

Look up and substitute a particular phrase in the document using Mongoose

I have data structured like this: { _id: 'some unique identifier', body: 'looking to acquire some mangoes', }, { _id: 'some unique identifier2', body: 'i want some mangoes and papaya& ...

Accepting undefined in rest parameter of typescript

I'm struggling with an exercise involving Function parameters: The maximum function below has the wrong type. To allow undefined in the rest arguments, you need to update the type of the rest parameter. Fortunately, you don't have to change the ...

Serialport node failing to receive data

I currently have an RS422 serial device connected to my Windows PC using a USB to serial cable. The cable incorporates an FTDI chip and I am utilizing the corresponding VCP drivers to communicate with the device through a COM port (COM3). https://i.sstati ...

Generating distinct identifiers for WebSocket and net.Socket connections

I am looking to assign unique identifiers to Websockets and net.Sockets so that each client can be identified by the identifier attached to the socket when a message is received. Previous findings: For WebSocket: Based on my research on Stack Overflow a ...

Is there a way to prevent IntelliJ from creating .js files when working with .ts source code?

Working on a mixed Java/Typescript project with Maven as the build tool, I utilize the frontend-maven-plugin to successfully build from the command line. However, I am encountering an issue with IntelliJ 2018.2 where it keeps transpiling .js files for my . ...