Reputation: 16764
I have a component which html structure look like:
<img mat-card-sm-image src="{{img}}" />
and in typescript
constructor(private loginService: LoginService) {
this.img = null;
this.loadImage();
}
loadImage = function () {
this.img = this.loginService.loginImg();
}
and login service:
loginImg() {
const url = "http://localhost:59078/api/image/login";
this.http.get(url, { responseType: 'blob' }).subscribe(result => {
console.log(result);
return result;
});
}
and the API Core controller
[HttpGet]
[AllowAnonymous]
[Produces("image/png")]
public IActionResult Login()
{
var file = Path.Combine(Directory.GetCurrentDirectory(),
"wwwroot", "images", "login.png");
return PhysicalFile(file, "image/png");
}
The idea that the image is not loaded... Why ?
Upvotes: 2
Views: 14306
Reputation: 4639
this.http.get(url, { responseType: 'blob' }).subscribe(result => {
console.log(result);
return result;
});
the return
here does nothing (especially since you aren't returning the http.get itself). The Service should return the observable http.get (without the subscribe) and then when you subscribe to it from your component, you change the img
variable from inside.
Here's how you can fix it
public img: string;
constructor(private loginService: LoginService) {
this.loadImage();
}
loadImage() {
this.loginService.loginImg().subscribe(result => {
this.img = result;
});
}
# Login service:
loginImg() {
const url = "http://localhost:59078/api/image/login";
return this.http.get(url, { responseType: 'blob' });
}
this is unrelated, but you might consider using an Angular lifecycle hook like ngOnInit
instead of the constructor for initializing variables
constructor(private loginService: LoginService) { }
public ngOnInit(): void {
this.loadImage();
}
Upvotes: 5