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

Learn how to dynamically import external modules or plugins using the import() functionality of TypeScript 2.4 within the production script generated by Angular CLI

Utilizing the typescript 2.4 [import()][1] feature has proven to be effective for dynamically loading modules. Testing this functionality has shown positive results, especially when importing modules and components located within the same directory. Howev ...

Getting data from Twilio Autopilot using PHP is not as complicated as it may seem

Hey everyone! I've encountered an issue with my PHP code that needs to receive some JSON (x-www-form-urlencoded) data from a Twilio Autopilot redirect. This is the code I'm currently using: $data = file_get_contents('php://input'); H ...

There appears to be an issue with the dynamic functionality of RouterLink in Angular 6

user-dashboard.html <ul class="nav flex-column"> <li class="nav-item"> <a class="nav-link" routerLink='/dashboard'>User Dashboard</a> </li> <li class="nav-item" *ngFor="let cat of categories; let i = in ...

The "void" type cannot be assigned to the type "ObservableInput<{}>"

I recently encountered this issue after updating to TS 2.2.2, and I suspect that is the root cause... While the code still functions properly, I am now seeing this error. I attempted various solutions such as returning an empty observable, catching the re- ...

Storing a new array inside a for loop in Swift can be achieved by

I am currently working with a for statement looping through movies and successfully printing the results for the keys "title" and "type". Now, I aim to showcase these outcomes in a ViewController or table cell. My main concern is regarding the creation ...

Encountering a hiccup while attempting to implement ngx-translate in an Angular library

I'm in the process of developing an Angular library, and I need to incorporate ngx-translate. In my other applications, I typically add TranslateModule.forRoot in the app.module file. import .... // AoT requires an exported function for factories exp ...

Dynamic Styling in Angular 2/4: A Modern Approach

Can someone help me with Angular 2/4 syntax for this code snippet? $('nav ul li a').click(() => { $(this).closest('li').addClass('active'); }); ...

Combining Java with Node.js modules

I'm interested in incorporating Angular2 as the client side framework and Java as the server side. However, I am unfamiliar with how to integrate Angular2 into a Java project. Is it advisable to initialize the NPM system within the Java project and in ...

What is the best way to fetch AJAX data posted with JSON format in a PHP script?

I am facing difficulty in accessing the data from a JSON string sent to a PHP file. JavaScript: $(document).ready(function() { //Creating a JavaScript Object var contact = { "client_email": $("#cleint_email").val(), "rep_name": $("#rep_ ...

Commit to calculating the total sum of each element using AngularJS

Trying to implement a like counter using Facebook's GRAPH API. I have a list of object IDs and for each ID, I make an API call to retrieve the number of likes and calculate a total. The issue arises as the API call returns a promise, causing only one ...

Compilation in TypeScript taking longer than 12 seconds

Is anyone else experiencing slow TypeScript compilation times when building an Angular 2 app with webpack and TypeScript? My build process takes around 12 seconds, which seems excessively slow due to the TypeScript compilation. I've tried using both ...

The functionality of d3 transition is currently non-existent

I've encountered an issue with my D3 code. const hexagon = this.hexagonSVG.append('path') .attr('id', 'active') .attr('d', lineGenerator(<any>hexagonData)) .attr('stroke', 'url(#gradi ...

Issue of Angular lazy loading not functioning with query parameters

Need help with implementing lazy loading using query parameters. I have a reactive search form where for each post, I want to load a lazy module that displays the search results in a table. The example on Stackblitz is similar to what I am trying to achi ...

What is the key to ensuring the content in your canvas adapts to different screen sizes

Greetings! I wanted to extract the values from this specific meta tag: <meta name="viewport" property="viewport" content="width-device-width, initial-scale=1"> To retrieve content from a meta tag using JavaScript, I used the following code snippet: ...

The HTML file that was typically generated by Webpack is now missing from the output

While working on my nodejs app using typescript, react, and webpack, everything was running smoothly. I was getting the expected output - an HTML file along with the bundle file. However, out of nowhere and without making any changes to my code, I noticed ...

Tips on updating checkbox background color after being selected

I've been working on creating checkboxes for seat selection in Angular using a TypeScript file, but I'm facing an issue where the background color of the checkbox doesn't change after checking them. Here's my TypeScript function: gener ...

What is the correct way to trigger an event specified as a string parameter in the emit() function?

My current goal is to pass the emit name as a string (for example, 'showComponent') from child to parent. I then want to trigger another emit in the emitAction(callbackName: string) function, and finally execute the showComponent() function. I&a ...

Retrieve JSON data from a server using jQuery following the submission of a form

Similar Question: JQuery Ajax Return value After filling out a login/register form, the server sends me to a JSON page. I am trying to retrieve that JSON data into a JavaScript/jQuery file without being redirected to that page. Is there a way to acce ...

Error: The TranslateService provider is not found and needs to be added to the

When attempting to make translation dynamic in angular2 using the ng2-translation package, I encountered an error message: Unhandled Promise rejection: No provider for TranslateService! zone.js:388Unhandled Promise rejection: No provider for TranslateSe ...

Using Javascript to establish a connection with a Joomla MySQL database

Recently, I was tasked with building a website in Joomla that utilizes a MySQL database. As part of this project, I am required to develop a JavaScript function that connects to the MySQL database. Do you have any advice or tips for me? ...