【问题标题】:Argument of type ‘Object’ is not assignable to parameter of type ‘string’ - Ionic Angular“对象”类型的参数不可分配给“字符串”类型的参数 - Ionic Angular
【发布时间】:2020-04-27 06:18:40
【问题描述】:

尝试使用 JSON 解析,但出现此错误: “对象”类型的参数不能分配给“字符串”类型的参数。

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 行中,我收到了该错误。可能是什么原因以及如何解决。

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>

【问题讨论】:

  • 这里JSON.parse()需要什么? event 响应是 JSON 格式的字符串吗?
  • @MichaelD 我需要在 uploadcare 中上传的网址,以便我可以在我的 html 代码中显示照片
  • 我已经发布了答案。请看看它是否适合你。

标签: angular ionic-framework


【解决方案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 请求并处理订阅中的错误也是一种很好的做法。

【讨论】:

  • 即使它有效,我也得到了图片,我可以在我的 HTML 中显示它,但我得到以下内容:属性'文件'在类型'对象'上不存在
  • 这可能是 TS Lint 错误,因为它没有对 API 返回的对象的任何引用。您可以改用this.imageURL = event['file']; 来克服它。
  • 真的很有帮助,非常感谢,它解决了我的问题
猜你喜欢
  • 1970-01-01
  • 2021-07-17
  • 2021-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-03
  • 1970-01-01
  • 2019-09-07
相关资源
最近更新 更多