将图像从API URL加载到angular 5组件中 [英] Load image from api url into angular 5 component

查看:83
本文介绍了将图像从API URL加载到angular 5组件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个html结构如下的组件:

I have a component which html structure look like:

<img mat-card-sm-image src="{{img}}" />

和打字稿

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

loadImage = function () {
   this.img = this.loginService.loginImg();
}

并登录服务:

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

和API Core控制器

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 ?

推荐答案

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

return 此处不执行任何操作(尤其是因为您不会返回http.get iteself)。服务应返回可观察到的http.get(不带订阅),然后从组件进行订阅时,从内部更改 img 变量。

the return here does nothing (especially since you aren't returning the http.get iteself). 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.

这里是解决方法

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' });
}

这无关,但是您可以考虑使用像<$这样的Anugular生命周期钩子c $ c> ngOnInit 而不是用于初始化变量的构造函数

this is unrelated, but you might consider using an Anugular lifecycle hook like ngOnInit instead of the constructor for initializing variables

constructor(private loginService: LoginService) { }

public ngOnInit(): void {
  this.loadImage();
}

这篇关于将图像从API URL加载到angular 5组件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆