Angular项目搜索后页面标题值重复问题求助
日期筛选后页面标题重复问题解决
问题背景
我有一个带日期筛选(开始日期、结束日期)的数据表格,点击搜索按钮触发getPrices()方法加载数据,同时该方法会调用getDetails()更新页面标题。但多次点击搜索后,标题内容会重复显示。
问题根源
在getDetails()方法中,使用+=拼接标题内容:
this.infoTitle += " " + res.ADVTITRE.BASIQUETITRE.LABEL + " (" + res.ADVTITRE.BASIQUETITRE.PLACELABEL + ")";
每次调用该方法时,都会在原有标题后追加新内容,而非覆盖旧内容,导致多次搜索后标题重复。
解决方法
方案1:直接覆盖标题内容
修改getDetails()方法,将+=改为=,直接赋值新标题,清空旧内容:
private getDetails(svm: string): void { this.service.getInstrumentInfo(svm).pipe( takeUntil(this.unsubscribe$) ).subscribe(res => { this.infoTitle = " " + res.ADVTITRE.BASIQUETITRE.LABEL + " (" + res.ADVTITRE.BASIQUETITRE.PLACELABEL + ")"; }); }
方案2:调用前清空标题
在getPrices()中调用getDetails()前,先重置infoTitle为空:
getPrices(): void { this.service.getInstrumentHistoryEquities(this.svm,this.model).pipe( takeUntil(this.unsubscribe$) ).subscribe(res => { if (res.HISTO.POINT.length > 0) { this.lines = res.HISTO.POINT.reverse(); } this.infoTitle = ""; this.getDetails(this.svm); }); }
方案3:优化请求逻辑(推荐)
标题信息基于路由参数svm,不会随日期筛选变化,因此只需在组件初始化时请求一次,无需每次搜索都调用:
ngOnInit(): void { let svm: string | null; svm = this.activatedRoute.snapshot.paramMap.get('svm'); if (!svm) { this.goBack(); return; } this.svm = svm; // 初始化时获取一次标题 this.getDetails(this.svm); this.getPrices(); } getPrices(): void { this.service.getInstrumentHistoryEquities(this.svm,this.model).pipe( takeUntil(this.unsubscribe$) ).subscribe(res => { if (res.HISTO.POINT.length > 0) { this.lines = res.HISTO.POINT.reverse(); } // 移除重复的getDetails()调用 }); }
该方案减少了不必要的API请求,从根源上避免标题重复问题。
内容的提问来源于stack exchange,提问作者pops1348
相关产品推荐
相关产品推荐

