尝试使用JSON解析,但出现此错误: 不能将“对象”类型的参数分配给“字符串”类型的参数。
U+FE56 ﹖ SMALL QUESTION MARK
在(事件)下的import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-uploader',
templateUrl: './uploader.page.html',
styleUrls: ['./uploader.page.scss'],
})
export class UploaderPage implements OnInit {
imageURL: string
constructor(public http: HttpClient) { }
ngOnInit() {
}
fileChanged(event) {
const files = event.target.files
const data = new FormData()
data.append('file', files[0])
data.append('UPLOADCARE_STORE', '1')
data.append('UPLOADCARE_PUB_KEY', '12d3f0b0b65cb448aa6b')
this.http.post('https://upload.uploadcare.com/base/', data).subscribe(event => {
console.log(event)
this.imageURL = JSON.parse(event).file
})
}
}
行中,我得到了该错误。可能是什么原因以及如何解决。
HTML:
this.imageURL = JSON.parse(event).file
答案 0 :(得分:1)
您很近。 POST请求中的the response似乎已经为JSON格式。您在这里不需要JSON.parse()
。尝试以下
this.http.post('https://upload.uploadcare.com/base/', data).subscribe(
event => {
this.imageURL = event.file;
},
error => { // handle error }
);
优良作法是在服务中发出实际的HTTP请求并处理订阅中的错误。