Angular 2 image src as function return

狂风中的少年 提交于 2020-07-18 11:01:59

问题


In my Angular 2 application i have a list of users "Users:any" wich contain the properties : name, job, age...etc , the problem is that to get the profile image i have to get the the id from of the image from the Users object, then use a web service getImage(ImageId), so i have this in my html

<div *ngfor="let user of users">
    <img [src]="getImage(user.profileImageId)"/>

In this case, i can't get the profile image displayed, i think the html is loading before the data ? any help?


回答1:


Just try this, this worked for me.

TS:

  getImage(id){
        return http.get(url/id);
    }

HTML:

<img [src]="getImage(user.profileImageId)" />



回答2:


if the webservice resolving the image url returns an Observable you have to resolve it. So to use a method to get this done you can use the async pipe:

Component:

getImage(id): Observable<string> {
    return http.get(url/id);
}

Template:

<img [src]="getImage(user.profileImageId) | async" />


来源:https://stackoverflow.com/questions/40511173/angular-2-image-src-as-function-return

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!