0

How are you doing?

I'm trying to render a value acquired from http in app.component.ts to the HTML but it isn't working. The value appears on console.log as a string but when I try to use it with this.date = dateObj it returns undefined.

When I access it from inside parseString() it doesn't work, but before it, it works. See on example for date = 'today'.

The HTML renders 'today' but not the value of dateObj. The value of dateObj is a string, just to remember.

HTML

<h2>{{date}}</h2>
<input type="submit" value="test" (click)="onClickMe()"/>

APP.COMPONENT.TS

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


@Component({
    '...'
})

export class AppComponent implements OnInit {
  title = 'testing';
  date: string;

  constructor() {}
  ngOnInit(): void{}


    onClickMe(){

      ** removed for brevity. HTTP REQUEST code **

      //retrieve http to data
      this.http.post(url, body, {
        headers: new HttpHeaders()
        .set('Content-Type', 'text/xml') 
        .append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS') 
        .append('Access-Control-Allow-Origin', '*')
        .append('Access-Control-Allow-Headers', "Access-Control-Allow-Headers, Access-Control-Allow-Origin, Access-Control-Request-Method")
  , responseType:'text'}).subscribe(data => {
        // Read the result field from the response in XML and transform to JSON.
           var parser = new DOMParser();
           var xmlDoc = parser.parseFromString(data,"text/xml");
           //today appears in HTML
            this.date = 'today';

          parseString(data, function (err, result) {
           var stringified = JSON.stringify(result);
           console.log(stringified);
           let jsonObject = JSON.parse(stringified);
           let dateObj = jsonObject['date'];

           //dateObj works fine on console.log but doesn't appear in HTML when rendering with {{date}}
            this.date = dateObj;


          });

    },
      (err: HttpErrorResponse) => {
        if (err.error instanceof Error) {
          // A client-side or network error occurred. Handle it accordingly.
          console.log('An error occurred:', err.error.message);
        } else {
          // The backend returned an unsuccessful response code.
          // The response body may contain clues as to what went wrong,
          console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
        }
      }
    );

  }




}

The question is, there is a way to do that? How should I do it so I could render the value in HTML?

4
  • Post output of console.log(jsonObject); Commented Nov 8, 2017 at 14:18
  • A good programming style dictates that opening and closing brackets should be on the same indentation level and overall your code is messy looking and a bit hard to read.(Mixed indentation, lot of code in single line ) Please take time of prettying up your code before asking on SO. It will be appreciated :) Commented Nov 8, 2017 at 14:37
  • @Satendra the output is {Dates: {…}} Commented Nov 8, 2017 at 15:54
  • @EinārsBistrovs I appreciate the tip! Commented Nov 8, 2017 at 15:57

1 Answer 1

4

assign it as this.date = dateObj; instead of date = dateObj;.

If that didn't fix, trigger a change detection by injecting the ChangeDetectorRef through constructor and calling the detectChanges() method.

import { ChangeDetectorRef } from '@angular/core';

constructor(private ref: ChangeDetectorRef){}

// call detectChanges() after this.date = dateObj;
this.date = dateObj;
this.ref.detectChanges();
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks for the answer! I've got a Cannot set property 'date' of undefined.
Could you please show the relevant component methods in full?
core.js:1350 ERROR TypeError: Cannot set property 'date' of undefined at eval (app.component.ts:113) at Parser.eval (parser.js:303) at Parser.EventEmitter.emit (events.js:81) at SAXParser.eval [as onclosetag] (parser.js:261) at emit (sax.js:624) at emitNode (sax.js:629) at closeTag (sax.js:889) at SAXParser.write (sax.js:1436) at Parser.exports.Parser.Parser.parseString (parser.js:322) at Parser.eval [as parseString] (parser.js:5)
(app.component.ts:113) is for this.date = dateObj;
But are you calling the parseString() method you have defined anywhere in the code? Still not clear what you have in the component and how the particular method gets called. All you have there is just the definition of parseString() but I can't see how you are calling it
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.