0

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>

3
  • 1
    What is the need of JSON.parse() here? Is event response a string in the format of a JSON? Commented Apr 26, 2020 at 22:04
  • @MichaelD i need a url of the upload in uploadcare so i can show the photo in my html code Commented Apr 26, 2020 at 22:15
  • 1
    I've posted an answer. Please see if it works for you. Commented Apr 26, 2020 at 22:20

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

even tho it works i get the pic and i can show it in my HTML but i get the following: Property 'file' does not exist on type 'Object'
That might be a TS Lint error because it doesn't have any reference to the object returned by the API. You could overcome it by using this.imageURL = event['file']; instead.
really helpful thank you very much, it solved my problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.