【问题标题】:How to pass a response from service to component?如何将响应从服务传递到组件?
【发布时间】:2017-05-17 21:06:39
【问题描述】:

我正在尝试将响应从我的服务传递给组件,以便我可以在 html 页面上显示它,但我不知道如何。

组件

uploadFile(): void {

  this.errors = null;

  let file = this.fileInput.nativeElement;
  if (file.files && file.files[0]) {
    let fileToUpload = file.files[0];
    this.getInfoService
      .uploadImage(fileToUpload)
      .subscribe(
        response => { console.log(response) },
        err => {
          //this.errors = err._body
          this.errors = err.json().image
          console.log("ERR", err.json().image)
        },
        () => console.log("()",'worked')
      );
  }

}

编辑:问题出在我的服务中。这是工作代码。

uploadImage(fileToUpload: any) : Observable<any> {

  let input = new FormData();
  input.append("image", fileToUpload);
  return this.http.post('http://Api.app/api/v1/upload', input)
    .map(
      (response: Response) =>  {
        // I was missing this part
        response.json()
      }
    );
}

【问题讨论】:

  • 那么你到底卡在哪里了?你可以在对象中看到你需要的东西,你真的不知道你是如何得到它们的吗?
  • 不,显然我不知道这就是我问的原因。我被困在关于如何将对象中的东西传递给组件的部分,以便我可以在我的 html 页面上显示它们

标签: angular lumen


【解决方案1】:

在您的组件上创建几个属性并将响应数据分配给这些属性。

image: any;
message: string;

uploadFile(): void {

  this.errors = null;

  let file = this.fileInput.nativeElement;
  if (file.files && file.files[0]) {
    let fileToUpload = file.files[0];
    this.getInfoService
      .uploadImage(fileToUpload)
      .subscribe(
        response => { 
            this.image = response.image;
            this.message = response.message;
       },
        err => {
          //this.errors = err._body
          this.errors = err.json().image
          console.log("ERR", err.json().image)
        },
        () => console.log("()",'worked')
      );
  }
}

在视图中显示您的消息:

{{ message }}

要显示嵌入的图像,您需要查看此帖子:

Angular2 Displaying an embedded image

【讨论】:

  • 我终于找到了问题所在。我在服务中记录了响应,但我没有分配它!我会更新 OP。
猜你喜欢
  • 2018-01-19
  • 2019-02-04
  • 2019-01-21
  • 2017-05-06
  • 1970-01-01
  • 2018-06-30
  • 1970-01-01
  • 2018-10-05
  • 1970-01-01
相关资源
最近更新 更多