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

How to pass a response from service to component?

我试图将我的服务的响应传递给组件,以便我可以在 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()
      }
    );
}

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

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

要显示嵌入图像,您需要查看此 post: