My backend API http://localhost:8300/api/picture
returns a string and I have tried following approaches:
( getpicture
is called on button click)
Approach 1:
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-auth-success',
templateUrl: './auth-success.component.html',
styleUrls: ['./auth-success.component.scss']
})
export class AuthSuccessComponent implements OnInit {
showImg: boolean = false;
imgUrl: string = "";
constructor(private http: HttpClient) { }
ngOnInit() {
}
getPicture(){
this.http.get("http://localhost:8300/api/picture",{ observe: 'response' })
.subscribe(
res => {
console.log(res);
this.onSuccess(res);
}, error => {
console.error("Some error while calling backed");
});
}
onSuccess(data: any){
this.imgUrl = data;
this.showImg = true;
}
}
And HTML:
<div>
<button (click)="getPicture()">Google Picture</button><br><hr><hr>
<img [src]="imgUrl" *ngIf="showImg">
</div>
Output:
"Some error while calling backed" found (i.e. error is printed)
Approach 2:
getPicture(){
this.http.get("http://localhost:8300/api/picture")
.map((res : Response)=> {
console.log(res); // correct value printed if below line is commented
this.imgUrl = res.text(); // compiler gives error at this line
})
.subscribe();
}
Output: I get compiler error:
Type Promise
<string>
is not assignable to type 'string'.
What am I missing?
EDIT: I have removed the custom error message that was getting printed
"Image not found"
with console.error(error)
as it was creating a confusion that my backend is returning this error.
The error message printed is:
e {headers: t, status: 200, statusText: "OK", url: "http://localhost:8300/api/picture", ok: false, …} error : {error: SyntaxError: Unexpected token h in JSON at position 0 at JSON.parse () at XMLHttp…, text: "https://lh3.googleusercontent.com/-46Nb-WbneSU/AAAAAAAAAAI/AAAAAAAAAAc/V7Pz0b9mxdw/photo.jpg"} headers : t {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ} message : "Http failure during parsing for http://localhost:8300/api/picture" name : "HttpErrorResponse" ok : false status : 200 statusText : "OK" url : "http://localhost:8300/api/picture"