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调用,提高性能。

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

相关内容

热门资讯

透视开挂"wepok... 透视开挂"wepoker如何设置透视"总是存在有辅助方法(哔哩哔哩)wepoker如何设置透视是不是...
透视详情"德普之星透... 透视详情"德普之星透视"其实有辅助工具(哔哩哔哩)1、德普之星透视免费脚本咨询教程、德普之星透视免费...
透视了解"hhpok... 透视了解"hhpoker德州牛仔视频"其实真的有辅助挂(哔哩哔哩)运hhpoker德州牛仔视频辅助工...
透视关于"aapok... 透视关于"aapoker ai插件"总是真的有辅助app(哔哩哔哩)1、玩家可以在aapoker a...
透视了解"wepok... 透视了解"wepoker透视脚本免费app"总是真的是有辅助脚本(哔哩哔哩)亲,关键说明,wepok...
透视详细"we-po... 透视详细"we-poker辅助"本来是有辅助插件(哔哩哔哩)1、进入游戏-大厅左侧-新手福利-激活码...
透视开挂"wepok... 透视开挂"wepoker私人局辅助"竟然真的有辅助插件(哔哩哔哩)1、wepoker私人局辅助免费辅...
透视辅助"poker... 透视辅助"pokerrrr2辅助"都是存在有辅助挂(哔哩哔哩)1、上手简单,内置详细流程视频教学,新...
透视透视"大菠萝78... 透视透视"大菠萝789辅助器下载"本来是真的辅助教程(哔哩哔哩)1、大菠萝789辅助器下载模拟器是什...
透视关于"hhpok... 透视关于"hhpoker脚本下载"本来存在有辅助app(哔哩哔哩)1、hhpoker脚本下载脚本辅助...