【问题标题】:How to return blob url after http request inside function in Angular如何在Angular中的函数内部http请求后返回blob url
【发布时间】:2019-08-28 18:32:17
【问题描述】:

我想做一个简单的聊天应用程序。我从服务中获取消息,模板中的 ngFor 打印消息。当我有消息图像类型时,我想从服务器获取 blob 并将 url 返回到图像 src。

这就是我所拥有的

HTML 模板

<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>

聊天组件

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

在这种情况下我该怎么办?我想在请求完成后返回结果。

【问题讨论】:

  • 返回 observable - return this.httpClient.get(...).pipe(map((res) =&gt; URL.createObjectURL(res)))
  • 在这种情况下,此方法将对象返回到模板。我将map(res =&gt; URL.createObjectURL(res)) 更改为map(res =&gt; 'test'),它仍然返回对象
  • 它返回一个observable,你需要解决它
  • @jonrsharpe 你能举个例子吗?在这种情况下我不知道该怎么做:/
  • 他们在教程中介绍了这一点:angular.io/tutorial

标签: angular typescript


【解决方案1】:

您的请求是异步的。在这种情况下,您在 get 请求中分配之前返回 result

关于您的问题,您可以尝试以下方法:

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

这样,你返回一个 observable 并且可以在任何你想要的地方订阅它。

【讨论】:

  • 在这种情况下,此方法将对象返回到模板。我将map(res =&gt; URL.createObjectURL(res)) 更改为map(res =&gt; 'test'),它仍然返回对象。
  • 是的。它返回一个Observable,它是一个对象。然后你可以subscribe 到这个 observable,比如getImageSrc('url').subscribe(image =&gt; /* Do something with your value */。关键是你不再局限于getImageSrc 方法体来做一些有价值的事情。 (另外,它是异步的也有优势)
猜你喜欢
  • 2018-01-05
  • 2021-06-28
  • 2015-12-28
  • 1970-01-01
  • 1970-01-01
  • 2015-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多