如何将响应从服务传递到组件?

问题描述 投票:0回答:1

我试图将响应从我的服务传递到组件,以便可以在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()
      }
    );
}
angular lumen
1个回答
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显示嵌入式图像

© www.soinside.com 2019 - 2024. All rights reserved.