【发布时间】:2021-06-01 06:41:10
【问题描述】:
我有一个 Angular 应用程序,我想上传一个文件并根据上传的文件显示一个字符串。
我对一个 Rest API 进行了 post 调用,这个 API 返回一个响应,我想显示这个响应的内容。但是有些问题是因为我可以console.log 响应的内容,但我无法正常显示它(即作为标签或类似内容)。
谁能告诉我该怎么做?
这里是component.html
<div>
<label class="image-upload-container btn btn-bwm">
<span>Select Image</span>
<input #imageInput type="file" accept="image/*" (change)="processFile(imageInput)">
</label>
<!--IT DOES NOT WORK Displays [object Object] -->
<input type=text name="prediction" [(ngModel)]="prediction" />
<!--IT DOES NOT WORK Displays [object Object] -->
{{prediction}}
</div>
这里是component.ts
import { Component, OnInit } from '@angular/core';
import { ImageService } from '../../services/image.service';
class ImageSnippet {
constructor(public src: string, public file: File) { }
}
@Component({
selector: 'app-image',
templateUrl: './image.component.html',
styleUrls: ['./image.component.css']
})
export class ImageComponent implements OnInit {
constructor(private imageService: ImageService) { }
prediction!: String;
ngOnInit(): void {
}
processFile(imageInput: any) {
const file: File = imageInput.files[0];
const reader = new FileReader();
reader.addEventListener('load', (event: any) => {
let selectedFile = new ImageSnippet(event.target.result, file);
this.imageService.uploadImage(selectedFile.file).subscribe(
(response) => {
this.prediction = response.toString();// IT DOES NOT WORK Displays [object Object]
// console.log() WORKS: it logs something like this: {prediction: "jeges, tensor([0.0530, 0.0999, 0.8471])"}
//which is the exact string that I want to display
console.log(response)
}
});
reader.readAsDataURL(file);
}
}
这里是service.ts
...
uploadImage(imageFile: File): Observable<Response> {
const formData = new FormData();
formData.append('imageFile', imageFile);
return this.http_client.post<Response>(this.url, formData);
}
...
这里是 API:
@app.route('/api/image-upload', methods=['POST'])
def call_predict():
imageFile = request.files['imageFile']
prediction = makePrediction(imageFile)
resp = make_response({"prediction": prediction}, 200)
resp.headers['Access-Control-Allow-Origin'] = '*'
return resp
【问题讨论】:
-
你在
response上有一个toString()调用,所以它会导致[object Object]显示,就像这样this.prediction = response -
无法编译。
Failed to compile. src/app/components/image/image.component.ts:34:11 - error TS2740: Type 'Response' is missing the following properties from type 'String': charAt, charCodeAt, concat, indexOf, and 37 more. 34 this.prediction = response; -
等一下,让我编辑一下
标签: angular typescript response console.log