D. Simon D. Simon - 4 months ago 34
JSON Question

Angular 2 Extract JSON based on selected form value

I am trying to extract a specific JSON values based on a user selected input that is the key and turn it into

. Currently, I am doing this which works for only extracting
test
:

// 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
}]
}


So far, I have tried passing the selected value as an argument to
getQuestions()
and
extractTest
so that I could return
body[selected] || {}
in
extractTest
, but when I do so, I get an undefined object in my subscribe function and the sort throws an error. I think I might be misunderstanding how map or subscribe works.

Does anybody have any ideas on how to do this?

Answer

probably your have to send parameter like this :-

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

if not solved your problem do comment here.