0

I am trying to pass a response from my service to component so I can display it on the html page but I cant figure out how.

The component

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

}

EDIT: Problem was in my service. Here is the working code.

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()
      }
    );
}
derrickrozay
  • 1,048
  • 3
  • 15
  • 37
  • So where exactly are you stuck? You can see the things you need in the object, do you really not know how you get at them? – jonrsharpe May 17 '17 at 21:18
  • No obviously I dont man thats why I'm asking. I'm stuck at the part about how to pass the things in the object to the component so I can display them on my html page – derrickrozay May 17 '17 at 21:26
  • https://angular.io/docs/ts/latest/tutorial/toh-pt6.html – jonrsharpe May 17 '17 at 21:33

1 Answers1

1

Create a couple of properties on your component and the assign the response data to those properties.

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

To display your message in your view:

{{ message }}

To display the embedded image, you will need to look at this post:

Angular2 Displaying an embedded image

Community
  • 1
  • 1
birwin
  • 2,524
  • 2
  • 21
  • 41
  • I finally figured out the problem. I was logging the response in the service but I wasnt assigning it! I'll update the OP. – derrickrozay May 17 '17 at 22:14