如何在Angular中的http请求后在函数中返回blob url [英] How to return blob url after http request inside function in Angular
问题描述
我想做一个简单的聊天应用程序.我从服务中获取消息,并且在模板中的ngFor打印消息.当我具有消息图像类型时,我想从服务器获取blob并将URL返回到图像src.
I want to make simple chat application. I get messages from service, and ngFor in template print the messages. When I have message image type, I want to get blob from server and return url to image src.
这就是我所拥有的
HTML模板
HTML Template
<div class="row message_chat_row" *ngFor="let chatMessage of chatMessages | async">
<div class="col chat_message_outer align-self-center">
<div class="row" [ngClass]="getChatMessageRowClass(chatMessage.sender_type)">
<div *ngIf="chatMessage.type === 'text' || chatMessage.type === 'info'" [innerHTML]="chatMessage.value" class="conpeek_chat_message_inner"></div>
<div *ngIf="chatMessage.type === 'image'" class="chat_message_inner">
<a (click)="downloadImg()"><img [src]="getImageSrc(chatMessage.value)"></a>
</div>
<div *ngIf="chatMessage.type === 'file'" class="chat_message_inner">
<a (click)="downloadFile()">{{chatMessage.filename}}</a>
</div>
</div>
</div>
</div>
聊天组件
Chat Component
getImageSrc(img_url) {
console.log('GET IMGAGE SRC', img_url);
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': $c.params.token
});
let result;
this.httpClient.get(img_url, {
responseType: "blob",
headers: headers
}).subscribe(res => {
result = URL.createObjectURL(res);
});
return result;
}
在这种情况下我该怎么办?我想在请求完成后返回结果.
What should I do in this situation ? I want to return result after request is done.
推荐答案
您的请求是异步的.在这种情况下,您在获取请求中分配 result
之前将其返回.
Your request is asynchronous. In this case you return result
before its assignation in your get request.
关于您的问题,您可以尝试执行以下操作:
Regarding your issue, you could try something like this:
getImageSrc(img_url): Observable<any> {
console.log('GET IMGAGE SRC', img_url);
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': $c.params.token
});
return this.httpClient.get(img_url, {
responseType: "blob",
headers: headers
}).pipe(
map(res => URL.createObjectURL(res))
);
}
这样,您可以返回一个可观察的对象,并可以在任意位置订阅它.
That way, you return an observable and can subscribe to it wherever you want.
这篇关于如何在Angular中的http请求后在函数中返回blob url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!