AngularUniversal-如果URL包含不安全字符,Transfer状态为空-重复XHR调用
创始人
2024-10-29 20:30:55
0

当使用Angular Universal时,如果URL包含不安全字符,可能会遇到Transfer状态为空的问题。同时,由于XHR调用的重复触发,这会导致性能问题,降低应用程序的整体速度。

解决这个问题的方法是使用DomSanitizer服务来深入清理URL,并确保其安全性。以下是示例代码:

import { Component, OnInit } from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; import { HttpClient } from '@angular/common/http'; import { ActivatedRoute } from '@angular/router'; import { TransferState, makeStateKey } from '@angular/platform-browser'; import { tap, map, filter } from 'rxjs/operators';

@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit {

constructor( private sanitizer: DomSanitizer, private http: HttpClient, private route: ActivatedRoute, private state: TransferState ) {}

ngOnInit() { const url = this.route.snapshot['_routerState'].url; const safeUrl = this.sanitizer.bypassSecurityTrustUrl(url);

const key = makeStateKey('data-' + safeUrl);
const urlData = this.state.get(key, null as any);
if (urlData !== null) {
  // 数据已经缓存了!
  console.log('From Cache');
  console.log(urlData);
  return;
}

this.http.get(safeUrl).pipe(
  filter(Boolean),
  map(res => res as any),
  map(res => {
    const data = res.data;
    this.state.set(key, data as any);
    return data;
  })
).subscribe(
  data => {
    console.log('From API', data);
  }
);

}

}

在这个示例中,我们使用了DomSanitizer服务来清理URL,并使用缓存的TransferState来避免重复的XHR调用,提高性能。

请注意,这只是一个示例代码,实际用法可能因

相关内容

热门资讯

重大来袭!微乐小程序自建房辅助... 重大来袭!微乐小程序自建房辅助工具插件,微乐家乡麻将自建房辅助app(开挂自建房)工具1、下载好微乐...
重磅来袭!微信微乐自建房辅助工... 重磅来袭!微信微乐自建房辅助工具,微乐小程序免费黑科技(开挂自建房)脚本1)微信微乐自建房辅助工具免...
专业讨论!微乐自建房辅助工具挂... 专业讨论!微乐自建房辅助工具挂,微乐小程序免费黑科技(开挂自建房)器1、让任何用户在无需微乐自建房辅...
终于清楚!微乐自建房辅助工具插... 终于清楚!微乐自建房辅助工具插件,微乐家乡麻将自建房辅助app(开挂自建房)app1、微乐家乡麻将自...
重大科普!微乐家乡麻将自建房辅... 重大科普!微乐家乡麻将自建房辅助app,微乐小程序免费黑科技(开挂自建房)技巧1、首先打开微乐家乡麻...
玩家必看秘籍!微信卡五星辅助器... 玩家必看秘籍!微信卡五星辅助器,微乐自建房脚本免费入口(开挂自建房)技巧1、任何微信卡五星辅助器透视...
一起来讨论!微乐自建房辅助工具... 一起来讨论!微乐自建房辅助工具插件,微乐自建房脚本免费入口(开挂自建房)教程1、超多福利:超高返利,...
实测分享!微乐家乡麻将自建房辅... 实测分享!微乐家乡麻将自建房辅助app,微乐家乡麻将自建房辅助app(开挂自建房)app微乐家乡麻将...
一分钟揭秘!微乐自建房辅助工具... 一分钟揭秘!微乐自建房辅助工具免费app,微乐自建房脚本免费入口(开挂自建房)攻略1、打开软件启动之...
必备辅助推荐!微信雀神麻将挂件... 必备辅助推荐!微信雀神麻将挂件开挂辅助,微乐小程序免费黑科技(开挂自建房)攻略1、起透看视 微信雀神...