将图像从 api url 加载到 angular 5 组件中

Sna*_*yes 3 .net-core angular

我有一个组件,其 html 结构如下所示:

<img mat-card-sm-image src="{{img}}" />
Run Code Online (Sandbox Code Playgroud)

并在打字稿中

constructor(private loginService: LoginService) {
    this.img = null;
    this.loadImage();
  }

loadImage = function () {
   this.img = this.loginService.loginImg();
}
Run Code Online (Sandbox Code Playgroud)

和登录服务:

loginImg() {
    const url = "http://localhost:59078/api/image/login";
    this.http.get(url, { responseType: 'blob' }).subscribe(result => {
      console.log(result);
      return result;
    });
}
Run Code Online (Sandbox Code Playgroud)

和 API 核心控制器

  [HttpGet]
  [AllowAnonymous]
  [Produces("image/png")]
  public IActionResult Login()
  {
     var file = Path.Combine(Directory.GetCurrentDirectory(),
                        "wwwroot", "images", "login.png");

     return PhysicalFile(file, "image/png");
  }
Run Code Online (Sandbox Code Playgroud)

图像未加载的想法......为什么?

Mil*_*eld 5

this.http.get(url, { responseType: 'blob' }).subscribe(result => {
  console.log(result);
  return result;
});
Run Code Online (Sandbox Code Playgroud)

return这里什么也不做(特别是因为你不必返回http.get本身)。服务应该返回可观察的 http.get(没有订阅),然后当你从你的组件订阅它时,你img从内部更改变量。

这是您可以修复它的方法

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' });
}
Run Code Online (Sandbox Code Playgroud)

这是不相关的,但您可能会考虑使用 Angular 生命周期钩子ngOnInit代替构造函数来初始化变量

constructor(private loginService: LoginService) { }

public ngOnInit(): void {
  this.loadImage();
}
Run Code Online (Sandbox Code Playgroud)