2

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 ?

Snake Eyes
  • 16,287
  • 34
  • 113
  • 221

1 Answers1

5
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();
}
MilesStanfield
  • 4,571
  • 1
  • 21
  • 32
  • This should work. I would like to add two more comments/best practices to it. 1. You can use OnInit hook to call the service instead of constructor, 2. You can use async pipe in html to subscribe to observable – Malai Apr 29 '18 at 16:03