4 回答
TA贡献1801条经验 获得超16个赞
如果要直接查看响应数据而不设置任何格式。
只需使用 JSON 管道{{ responseData | json }}
您需要为控制器中的任何变量分配响应
responseData: any;
submitForm() {
var formData: any = new FormData();
formData.append("inputText", this.form.get('inputText').value)
this.http.post('http://127.0.0.1:5000/predictSentiment', formData).subscribe(
(response) => { this.responseData = response }, // <-- assign the value here
(error) => { console.log(error) }
);
}
然后在模板中使用 JSONpipe 绑定变量
<div class="card col-md-6">
<div class="card-body">
<h2 class="card-title">Output:</h2>
<div>
{{responseData | json }}
</div>
</div>
</div
TA贡献1735条经验 获得超5个赞
根据经验,尽量不要从 模板表达式 (如 、 和 ) 调用函数。它们通常被调用的次数比看起来的次数要多。*ngFor="let data of submitForm()*ngIf="submitForm()"{{ submitForm() }}
当然,我们可以通过更改检测策略来解决此行为,但这将是解决问题的解决方案,否则可以轻松解决。
在您的例子中,您可以在局部变量中分配HTTP响应,并在模板中循环访问它。请尝试以下操作
控制器
form: FormGroup;
responseData: any = []; // <-- define a variable and assign an empty array
constructor(
public fb: FormBuilder,
private http: HttpClient
) {
this.form = this.fb.group({
inputText: ['']
})
}
ngOnInit() {}
submitForm() {
var formData: any = new FormData();
formData.append("inputText", this.form.get('inputText').value)
this.http.post('http://127.0.0.1:5000/predictSentiment', formData).subscribe(
(response) => { this.responseData = response }, // <-- assign the value here
(error) => { console.log(error) }
);
}
模板
<ng-container *ngIf="responseData.length > 1">
<div class="card col-md-6">
<div class="card-body">
<h2 class="card-title">Output:</h2>
<div *ngFor="let data of responseData">
{{data?.response}}
</div>
</div>
</div>
</ng-container>
TA贡献1810条经验 获得超5个赞
您正在 *ngFor 中调用方法 submitForm(),但它没有返回任何内容。相反,您可以声明一个变量并分配 repsonse
data : any;
this.http.post('http://127.0.0.1:5000/predictSentiment', formData).subscribe((response) =>
this.data = response,
(error) => console.log(error)
)
并将您的 HTML 更改为
<div class="card-body">
<h2 class="card-title">Output:</h2>
<div *ngFor="let data of data">
{{data.response}}
</div>
</div>
TA贡献1824条经验 获得超8个赞
您可以有一个变量,您可以在其中设置收到的响应。
form: FormGroup;
result: any[];
constructor(
public fb: FormBuilder,
private http: HttpClient
) {
this.form = this.fb.group({
inputText: ['']
})
}
ngOnInit() {}
submitForm() {
var formData: any = new FormData();
formData.append("inputText", this.form.get('inputText').value)
this.http.post('http://127.0.0.1:5000/predictSentiment', formData).subscribe(
(response) => { this.result = response; },
(error) => console.log(error)
)
}
在 html 中绑定变量以显示内容:
<div class="card col-md-6">
<div class="card-body">
<h2 class="card-title">Output:</h2>
<div *ngFor="let data of results">
{{data.id}} - {{data.name}}
</div>
</div>
</div>
示例:如果返回的数据如下所示:
[
{ id: 1, name: "XXX"},
{ id: 2, name: "YYY"},
]
输出为:
1 - XXX
2 - YYY
添加回答
举报
