“对象"类型的参数无法分配给“字符串"类型的参数-Ionic Angular [英] Argument of type ‘Object’ is not assignable to parameter of type ‘string’ - Ionic Angular

查看:56
本文介绍了“对象"类型的参数无法分配给“字符串"类型的参数-Ionic Angular的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试用JSON解析,但出现此错误:无法将类型为对象"的参数分配给类型为字符串"的参数.

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
    })
  }


}

在(事件)下的 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.

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>

推荐答案

您很亲密.似乎来自POST请求的响应已经为JSON格式.您在这里不需要 JSON.parse().尝试以下

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 }
);

优良作法是在服务中发出实际的HTTP请求并处理订阅中的错误.

It is also good practice to make the actual HTTP request in a service and to handle the error in the subscription.

这篇关于“对象"类型的参数无法分配给“字符串"类型的参数-Ionic Angular的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆