spaceman
spaceman

Reputation: 649

Angular not rendering value from app.component in HTML

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?

Upvotes: 0

Views: 1106

Answers (1)

amal
amal

Reputation: 3170

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();

Upvotes: 4

Related Questions