【问题标题】:Http request starts leakingHttp 请求开始泄漏
【发布时间】:2021-08-21 09:25:52
【问题描述】:

我正在使用此代码通过 translateBack

翻译每个单词
<span *ngFor="let word of getWords(); index as i">
  <button (click)="speak(word)"
  [matTooltip]="translateBack(word) | async">{{word}}</button>
</span>

translateBack 在哪里

translateBack(word: string) {
  const options = {q: word, source: 'ru-RU', target: 'en-GB'};
  return this._http.post(url + key, options).pipe(
    take(1),
    map((res: any) => res.data.translations[0].translatedText)
  )
}

但在我的控制台中,它显示了一个永无止境的 http 请求日志。怎么只拿一个? (我试过了(1))

【问题讨论】:

  • 对于for循环中的每个按钮,您都在发出http请求,因此程序在这里发出大量http请求是有意义的。对于 http 请求,take(1) 并不是很有用,因为 Post/Get 请求(使用 angular-http)只返回一次并完成。
  • 当您从模板调用函数和方法时,它们也会在每个“滴答”上被调用;我建议将translateBack 制作成管道本身。
  • @jonrsharpe 真的在每个“滴答声”上吗?我认为在每次滴答后事情都会发生变化的角度更新。
  • 感谢@jonrsharpe 的建议,管道是否意味着您避免每次滴答都重新渲染?

标签: angular observable


【解决方案1】:

在 Angular 中,最好使用 forkJoin 循环调用:

使用 forkJoin 一次翻译所有单词

translateWord=forkJoin(this.getWords().map(word=>{
   const options = {q: word, source: 'ru-RU', target: 'en-GB'};
   //I suppose is this.url and this.key
   return this._http.post(this.url + this.key, options).pipe(map(
        (res:any)=>({word:word,translate:res.data.translations[0].translatedText})))
   }
   ))

并使用

<span *ngFor="let word of translateWord|async; index as i">
  <button (click)="speak(word.word)"
  [matTooltip]="word.translate">{{word.word}}</button>
</span>

【讨论】:

  • 很好的答案,谢谢,但我收到了这个打字稿错误:word.word 和 word.translate 的任何对象都是 'unknown'.ngtsc(2571) 类型
  • ::glups:: 我想是 this.getWords().map( x =>{...} (is this.getWords().map( word =>{...} - 刚刚在代码中更正-
猜你喜欢
  • 1970-01-01
  • 2022-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-05
  • 2014-06-20
  • 2011-08-18
相关资源
最近更新 更多