Rob W
Rob W

Reputation: 611

Assign XML from http request to an array

I'm hoping that you can help a school teacher in need! I'm making an HTTP request to our school database and it is returning the data as XML. I wish to store that data in an array so that I can display information about each student in an Angular app. The code in my students-list.component.ts is:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

declare var require: any; // this prevents the require error for rxjs

@Component({
  selector: 'students-list',
  template: `
    <nav-bar></nav-bar>
    <h1>Students</h1>
    <hr/>
    <student-thumbnail [student] = "students"></student-thumbnail>
  `,
  styleUrls: ['./students-list.component.css'],
})
export class StudentsListComponent implements OnInit {
  constructor(private http: HttpClient) {}
  students = [1, 2, 3];

  url =
    'https://'our site';

  xmlBody = `<?xml version="1.0" encoding="utf-8" ?><Filters><MethodsToRun><Method>Pupil_GetCurrentPupils</Method></MethodsToRun></Filters>`;

  ngOnInit() {
    this.http
      .post(this.url, this.xmlBody, { responseType: 'text', observe: 'body' })
      .subscribe((findings) => {
        const xml2js = require('xml2js');

        xml2js.parseString(findings, function (err, result) {
          if (err) {
            console.log(err);
          }
          console.log(result.iSAMS.PupilManager[0].CurrentPupils[0].Pupil);
        });
      });
  }
}
in the console I get the following information and would like to store that in the students array in order to be able to show the data to staff (name, email address etc). I've tried assigning to the this.students variable in the ngOnInit method but that isn't working. Could somebody please help me with that process?

enter image description here

Upvotes: 1

Views: 169

Answers (1)

Aakash Garg
Aakash Garg

Reputation: 10979

Change code to :-

ngOnInit() {
    this.http
      .post(this.url, this.xmlBody, { responseType: 'text', observe: 'body' })
      .subscribe((findings) => {
        const xml2js = require('xml2js');

        xml2js.parseString(findings, (err, result) => {
          if (err) {
            console.log(err);
          }
          this.students = result.iSAMS.PupilManager[0].CurrentPupils[0].Pupil;
        });
      });
  }

Its about lexical scoping, use of arrow function was required instead of normal callback function.

Upvotes: 2

Related Questions