Filtering JSON Data in Angular 2 Using Form Selection

I need help extracting specific JSON values based on user-selected input keys and converting them into QuestionBase<any>[]. Currently, my code successfully extracts values for the key "test" only:

// dropdown HTML
<select class="form-control" name="test" id="test" (ngModel)="test" (change)="onSelectChange($event, test.form)">
       <option selected disabled hidden style='display: none' value=''></option>
       <option value="test">Test</option>
       <option value="other">Other</option>
</select>

// question-list.component.ts
onSelectChange($event: any, form: NgForm) {
    this.getQuestions();
}
getQuestions() {
    this.questionService.getQuestions()
        .subscribe(questions => this.questions = questions.sort((a, b) => a.order - b.order),
        error => this.errorMessage = <any>error);
}

// question.service.ts
getQuestions(): Observable<QuestionBase<any>[]> {
return this.http.get(this.jsonUrl)
  .map(this.extractTest)
  .catch(this.handleError);
}
private extractTest(res: Response) {
 let body = res.json();
 return body["test"] || {};
}

// JSON
{
    "test": [{
               key: 'firstName',
               label: 'First name',
               value: 'Bombasto',
               required: true,
               order: 1
            }, {
              key: 'brave',
              label: 'Bravery Rating',
              options: [
               {key: 'solid',  value: 'Solid'},
               {key: 'great',  value: 'Great'},
               {key: 'good',   value: 'Good'},
               {key: 'unproven', value: 'Unproven'}
               ],
              order: 2
            }],
    "other": [{
            key: 'emailAddress',
            label: 'Email',
            type: 'email',
           order: 1
        }]   
}

I've attempted passing the selected value as an argument to getQuestions() and extractTest in order to return body[selected] || {} in extractTest, but it results in an undefined object in my subscribe function and triggers an error during sorting. I suspect my misunderstanding of how map or subscribe functions work might be causing the issue.

Any suggestions on how to tackle this problem would be greatly appreciated.

Answer №1

It may be necessary for you to send a parameter like this :-

// question.service.ts
getQuestions(): Observable<QuestionBase<any>[]> {
return this.http.get(this.jsonUrl)
  .map(res => this.extractTest(res))  //remember to pass a parameter here and return it to the subscribe function
  .catch(this.handleError);
}
private extractTest(res: Response) {
 let body = res.json();
 return body["test"] || {};
}

If this does not resolve your issue, please leave a comment below.

Update

In my opinion, when using .map with multiple lines, it is necessary to use the return keyword to return a value back. However, when using a single line .map, there is no need to use return. This is the main difference in my view. So, in your case, try this:

return this.http.get(this.jsonUrl).map(res => { return this.extractTest(res, selected); }) .catch(this.handleError);

instead of this

return this.http.get(this.jsonUrl).map(res => { this.extractTest(res, selected); }) .catch(this.handleError);

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

Combining arrays in JSON with the power of Groovy 2.4

Below is the JSON input I have, where I am attempting to merge scheduleDetails with the same ID: {"orderLines": [{ "ID": "001", "scheduleDetails": [{ "address": { ...

Error in Angular-CLI: The return type of a public method from an exported class is referencing the name 'ErrorObservable' from an external module, but it cannot be named as such

Upon completing the development of an app that mirrors an existing Angular 2 (non-cli) application, I am encountering errors in several of my files now that the project has been transitioned to Angular-CLI. I am puzzled as to why these errors are arising i ...

Using NextJs <Script> is only effective after a page has been reloaded

Currently delving into the world of NextJS and encountering an issue with integrating a third-party ebay script onto one of my route pages. The script only seems to appear sporadically upon reloading the page. However, when navigating to the store page via ...

Using an asynchronous pipe filter with the ngFor loop in Angular 2 for efficient data

I have a JSON array that I need to iterate through in order to display data using an NGfor Loop. My goal is to apply filters after the data has been loaded to refine the results. The issue I am facing is that my pipe filter is returning 'cannot read p ...

Sending json data to an MVC controller

I am attempting to send data using jQuery ajax to an Asp.Net MVC controller. The class I am using is as follows: public class InnerStyle { [JsonProperty("color")] public string HeaderColor { get; set; } [JsonProperty("font-size")] publ ...

Why doesn't Angular 6 show the results of Next right away?

Although I don't have the code on hand, this is more of a theoretical question that I believe can still be answered. In my scenario, there is a MsgService that provides messages to components. When I update or set messages in the service from one of ...

Guide to incorporating external CSS and JavaScript into an Angular 2 project with Express.js and Node.js

As a newcomer to Angular2 and NodeJs, I am eager to learn how to integrate external CSS and JS in an Angular2 and Nodejs express app. Specifically, I am looking to integrate a bootstrap admin theme into my Nodejs application. The screenshots below provide ...

Can :[Interface] be considered a correct array declaration in Typescript?

My TypeScript codebase is filled with code snippets like the one below... export interface SomeType { name: string; } export interface SomeComposedType { things: [SomeType]; } Everything was working smoothly until I started experiencing issues su ...

Retrieving and transforming data from a JSON format using Regular Expressions

Hello there, I have a task that requires extracting data from the token_dict object received through the api and converting it. Here's an example: "token_dict": { "0x13a637026df26f846d55acc52775377717345c06": { "chain&qu ...

The specified field type of Int! was not included in the input

I encountered a GraphQL error that states: "Field JobInput.salarys of required type Int! was not provided." While working on my mutation, I have declared three variables and I'm unsure if the syntax "salarys: number;" is correct. Can someone please c ...

Differentiating between module-level variables and local variables in TypeScript

Check out this module: export module Example{ let client : any; export function myExample(customer: string) { // How can I access the variable "client" at the module level inside this function? // Should I consider using Pascal Ca ...

Mastering the skill of extracting information from nested JSON objects with Java

i am having difficulty extracting values from a JSON object that I receive when making a call to a REST API. MY AIM: I want to iterate through each data set in the data array, check the value of TRAN_ID, and take appropriate action based on it. here is t ...

Confirming the dependencies of Angular modules versions

Coming from a Java/Maven background, I find understanding versioning in npm to be challenging and somewhat delicate. How can I ensure that all versions in an npm package are accurate? It appears that certain parts of @angular have versions that are separa ...

Converting an image URL to a bitmap representation

Hey there, I'm new to working with Android. I have an activity class that retrieves a JSON string from a URL and converts the JSON array into an object. The issue I'm facing is that the image is being returned as a TextView instead of displaying ...

Having trouble changing the title of a highchart using @input?

In my StreamsComponent, I set up my Highcharts like this: export class StreamsComponent implements OnInit { @Input() platform: string = ""; @Input() title: string = ""; series: any[] = []; Highcharts: typeof Highcharts = Highc ...

What prevents the right side of this conditional type from being defined as never?

During type-checking time, I have a rule to enforce regarding the parameters that can be passed to my function. The type is described in the following code snippet: type CheckConf<TConf extends SupportedConf> = { [Key in keyof TConf]: TConf[Key] e ...

What is the best way to reset a dropdown list value in angular?

Is there a way to erase the selected value from an Angular dropdown list using either an x button or a clear button? Thank you. Code <div fxFlex fxLayout="row" formGroupName="people"> <mat-form-field appearance=&quo ...

Enhance the angular 2 dependencies within the angular2-cli project

After experimenting with Angular 2 and following the guide on their website, I attempted to switch to Angular 2 CLI. However, the Angular 2 CLI project does not have the latest dependencies, resulting in errors from the compiler related to certain commands ...

Order JSON data based on a predetermined list of keys using JavaScript

Imagine having a JSON list called LIST A: LIST A [ { "address": "wellington lane", "age": "23", "country": "Australia", "name": "Mike", "profession&q ...

Parsing JSON with a variable amount of objects and keys

I am facing a challenge with deserializing a JSON string in my WPF application using System.Net.Json. The issue arises when handling a subobject (node) in the tree that contains a variable number of properties/nodes with variable names. A simplified exampl ...