你好吗?
我试图将从app.component.ts中的http获取的值渲染为HTML,但它不起作用。
该值作为字符串显示在console.log上,但是当我尝试将其与this.date = dateObj
一起使用时,它将返回undefined。
当我从 parseString()内部访问它时,它不起作用,但在它之前,它可以正常工作。请参阅示例 date ='今天' 。
HTML呈现'今天' ,但不是 dateObj 的值。 dateObj 的值是一个字符串,只是为了记住。
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}`);
}
}
);
}
}
问题是,有办法做到这一点吗?我应该怎么做才能在HTML中呈现值?
答案 0 :(得分:4)
将其指定为this.date = dateObj;
而不是date = dateObj;
。
如果没有解决,请通过注入ChangeDetectorRef
构造函数并调用detectChanges()
方法来触发更改检测。
import { ChangeDetectorRef } from '@angular/core';
constructor(private ref: ChangeDetectorRef){}
// call detectChanges() after this.date = dateObj;
this.date = dateObj;
this.ref.detectChanges();