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

查看:26
本文介绍了将图像从 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 核心控制器

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 本身).服务应该返回可观察的 http.get(没有订阅),然后当你从你的组件订阅它时,你从内部更改 img 变量.

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.

解决方法如下

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

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

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

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

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