问题
Trying to parse with JSON but i get this error: Argument of type 'Object' is not assignable to parameter of type 'string'.
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
})
}
}
In the line this.imageURL = JSON.parse(event).file
under (event) i get that error. What could be the cause and how to fix it.
The HTML :
<ion-header>
<ion-toolbar>
<ion-title>Upload Image</ion-title>
</ion-toolbar>
</ion-header>
<ion-content padding>
<div class="camera"> </div>
<input type="file" (change)="fileChanged($event)"/>
<img *ngIf="imageURL" src="https://ucarecdn.com/{{ imageURL}}/"/>
</ion-content>
回答1:
You are close. It appears the response from the POST request is already in JSON format. You don't need the JSON.parse()
here. Try the following
this.http.post('https://upload.uploadcare.com/base/', data).subscribe(
event => {
this.imageURL = event.file;
},
error => { // handle error }
);
It is also good practice to make the actual HTTP request in a service and to handle the error in the subscription.
来源:https://stackoverflow.com/questions/61448660/argument-of-type-object-is-not-assignable-to-parameter-of-type-string-ioni