Attempting to access a specific JSON key using Observables

Apologies for the question, but I'm relatively new to Typescript and Ionic, and I find myself a bit lost on how to proceed.

I have a JSON file containing 150 entries that follow a quite simple interface declaration:

export interface ReverseWords {
id: number;
todo: string;
solution: string;}

Additionally, I have a service in place that reads the JSON file and returns an Observable of this particular type (ReverseWords)

getReverseWords() {
return this.http.get<ReverseWords>('/assets/data/reves.json');}

In my .ts file, I utilize the service to retrieve all the content from the JSON file. However, I'm struggling with extracting just one entry based on a random position.

In the .ts file:

reverseWords: Observable<ReverseWords>; // Contains all JSON content
reverseWordsSelected: Observable<ReverseWords>; // Intended to hold a single entry

Within ngOnInit():

this.reverseWords = this.dataservice.getReverseWords();

Thus far, everything seems fine as I can view all the content and log it to the console. Since I'm using Observables, subscription is required to access the information. Despite employing rxjs/operators pipe and filter, nothing appears in the Chrome developer console (no errors either).

const reverseWordSelectedByPosition = this.reverseWords.pipe(filter(reverseWord => reverseWord.id === randomPosition));
  reverseWordSelectedByPosition.subscribe(console.log);

If anyone could provide guidance on what I might be overlooking, it would be greatly appreciated.

Furthermore, I experimented by adjusting the service as follows:

getReverseWords() {
return this.http.get<ReverseWords[]>('/assets/data/reves.json');}

Subsequently updated the .ts file:

reverseWords: Observable<ReverseWords[]>;

Regrettably, the same issue persists.

Interestingly, when conducting a simple test in the .ts file like so:

const test = from([
     {
        id: 1,
        todo: 'chapter',
        solution: 'r-e-t-p-a-h-c'
     },
     {
        id: 2,
        todo: 'claustrofobia',
        solution: 'a-i-b-o-f-o-r-t-s-u-a-l-c'
     },
     {
        id: 3,
        todo: 'keyboard',
        solution: 'd-r-a-o-b-y-e-k'
     }
  ]);

All functions flawlessly, displaying only one entry in the log at a time according to selection.

Any advice or assistance would be greatly welcome!

Per TotallyNewb's recommendation, I've included an example of the JSON file comprising just three entries:

[
  {
    "id": 1,
    "todo": "chapter",
    "solution": "r-e-t-p-a-h-c"
  },
  {
    "id": 2,
    ": "claustraphobia",
    ":solution": "a-i-b-o-f-o-r-t-s-u-a-l-c"
  },
  {
    "id":: 3,
    "oto""kbdraeoyekwd",
    "oltisuird": "jeshcefiejiefijeijfei"
   ]

Answer №1

If you're looking to obtain the entire array, consider utilizing map

this.reverseWords.pipe(
    map((items) => items[Math.floor(Math.random() * items.length)]), // Generates a random index based on the array length
  )
  .subscribe(console.info);

To pass the outcome to reverseWordsSelected, convert it to a Subject and transmit the value using .next() within the subscription of reverseWords.

For a functional demonstration, visit this stackblitz link

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

Methods in Ionic to call an external JavaScript file from TypeScript

Having a JSON list stored in a JavaScript file, my objective is to filter it using TypeScript before sending the filtered results to the HTML homepage. However, I encountered an issue within the HTML file. It's worth mentioning that when running the ...

Integrating one service into another allows for seamless access to the imported service's properties and methods within an Angular

After reviewing the content at https://angular.io/guide/dependency-injection-in-action, it appears that what I am trying to achieve should be feasible. However, I encounter this error when attempting to invoke a method on my injected service from another s ...

What is the best way to dynamically adjust the width of multiple divisions in Angular?

I am currently working on an angular project to create a sorting visualizer. My goal is to generate a visual representation of an array consisting of random numbers displayed as bars using divisions. Each bar's width will correspond to the value of th ...

Have there been any updates to ngFormControl in @angular/forms version 0.3.0?

I recently updated my Angular application from rc4 to rc5, along with upgrading angular forms from version 0.2.0 to 0.3.0. After the update, I started encountering an error that seems to be related to a change in ngFormControl within forms 0.3.0. zone.js: ...

Error Encountered: Unexpected Identifier in Angular 7 External jQuery Plugin

Struggling to convert a jQuery template to Angular7, I'm facing an issue with loading .js files from the assets folder in the original template to make it functional. Upon starting the application with: ng serve, I encounter the following error in th ...

Discovering numbers within a JSON object and extracting them - a step-by-step guide

If I have a JSON object coming from a random dataset and want to search through it to manipulate the number values, how can I achieve this? Looping through the object using for...of allows me to get the keys, but I'm unsure how to access every key-val ...

Develop interactive web applications using Typescript

Having difficulty compiling and executing the project correctly in the browser. The "master" branch works fine, but I'm currently working on the "develop" branch. It's a basic web project with one HTML file loading one TS/JS file that includes i ...

Issues with executing code within the react package for Yahoo Finance 2

I am currently in the process of developing a React application using Vite. The purpose of my app is to retrieve stock-related information from Yahoo using the yahoo-finance2 package. Interestingly, when I run the code as a standalone JavaScript file, eve ...

Can a discriminated union be generated using mapped types in TypeScript?

Imagine you have an interface called X: type X = { red: number, blue: string } Can a union type Y be created using mapped types? If not, are there other ways to construct it at the type level? type Y = { kind: "red" payload: number } | ...

PHP Error - Noticed a non-existent constant 'x' being used in the code, assumed it to be 'x

How to Retrieve Data from a Table, Pass it to the Controller in JSON Format, and Display it in a View Using AngularJS I am looking to extract data from a controller's json-encoded variable and showcase it on a view page through angularjs <div cla ...

What is the best way to eliminate the initial key from a JSON object

How can I remove the first index in a JSON object? JSON: {"data":[{"label":"Data","data":1},{"label":"Website","data":1}]} I need: [{"label":"Data","data":1},{"label":"Website","data":1}] When I try to delete .data, it outputs object{} JavaScript c ...

Exploring the Dynamic Display of Nested JSON Objects in Angular 6

Struggling with a complex issue and feeling lost on how to approach it. I'm currently working with Angular 6. The challenge at hand involves handling JSON data in my project. While accessing simple data like "id" or "certificate" is easy, I'm en ...

Enhancing the format of multidimensional JSON combining using PHP and JSON

My current JSON output looks like this: [{"dateClose":"2012-07-06","countno":"6","cumulative_sumc":"103"}],[{"dateOpen":"2012-05-29","openNo":"73","cumulative_sum":"73"}] What I actually want is to have it in one multidimensional array as shown below: ...

Managing Visual Studio Code Extension Intellisense: A Guide

I am looking to create an extension I recommend using "CompletionList" for users. Users can trigger completion by running "editor.action.triggerSuggest" The process of my extensions is as follows: Users input text If they press the "completion command," ...

Issue arises when attempting to convert a class object into JSON which includes a datetime field. This specific error message is displayed: "TypeError: Object of

I'm having trouble converting an object into JSON. While converting from JSON to an object was straightforward, I encountered an error when using the dumps method: TypeError: Object of type datetime is not JSON serializable. Is it possible to convert ...

How to eliminate all special characters from a text in Angular

Suppose I receive a string containing special characters that needs to be transformed using filter/pipe, with the additional requirement of capitalizing the first letter of each word. For instance, transforming "@!₪ test stri&!ng₪" into "Test Stri ...

Looking to include a badge within the nebular menu

Can someone assist me with adding a badge to the Nebular menu to display the inbox count dynamically? Any help would be greatly appreciated. Thanks! import { NbMenuItem } from '@nebular/theme'; export const MENU_ITEMS: NbMenuItem[] = [ { ti ...

When running Javascript code locally, the function works perfectly fine. However, once published, the function encounters a

After spending hours working on cascading dropdown lists and finally getting them to function properly, I published the project only to find that it didn't work as expected. The second list failed to populate. Upon checking Firebug's console, an ...

Using spyOn to fake Observable responses - a step-by-step guide

My service is set up to request JSON data through HTTP: export class TodosService { constructor(private http: HttpClient) {} getTodos(): Observable<any> { return this.http.get<any>('https://jsonplaceholder.typicode.com/todos') ...

Occasionally, angulafire2's getDownloadURL() function may fail to work with Angular. Could this be due to asynchronous processes?

Receive a 404 error when trying to access . Firebase is reporting a download link error with the following message: "Firebase Storage: Object 'hw04.docx' does not exist." Below is the code snippet related to this issue. upload(event) { cons ...