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()
}
);
}
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:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.