首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在重新加载页面时将动态添加的<title>保留在角中

在重新加载页面时将动态添加的<title>保留在角中
EN

Stack Overflow用户
提问于 2021-12-13 12:26:40
回答 1查看 480关注 0票数 1

在刷新页面以保存已动态添加的标记时,是否存在这种可能性?

现在,当我刷新页面时,在加载时,标题标记会更改为原始标记,这是我在index.html中设置的。加载页面后,标题标签将返回到动态添加的正确标记。但是,当页面刷新时,我希望标题标签保持不变。

这是我的app.component.ts:

代码语言:javascript
复制
this.router.events.pipe(
      filter((event) => event instanceof NavigationEnd),
      map(() => this.activatedRoute),
      map((route) => {
        while (route.firstChild) route = route.firstChild;
        return route;
      }),
      filter((route) => route.outlet === 'primary'),
      mergeMap((route) => route.data)
    )
      .subscribe((event) => {
        console.log(event)
        this.translateService.get(event['title']).subscribe(name => {
          this._seoService.updateTitle(name);
        });
        this._seoService.updateDescription(event['description'])
      });
EN

回答 1

Stack Overflow用户

发布于 2021-12-13 13:06:08

一种方法是使用局部存储将动态标题存储在其中。下面是一个简单的示例,其中我将标题存储在本地存储中并刷新页面,并将标题保留回原处。Angular提供了一个名为标题的服务,它允许我们随时动态更新标题。

代码语言:javascript
复制
<button (click)="setItem()">Click to set a title</button>

<p *ngIf="showInfo" >Refresh the page now :)</p>
代码语言:javascript
复制
export class AppComponent implements OnInit {
  showInfo = false;  

  constructor(private titleService: Title) {}

  ngOnInit() {
    this.getItem();
  }

  setItem() {
    localStorage.setItem('title', 'Hey World!');
    this.showInfo = true;
    this.getItem();
  }

  getItem() {
    if (localStorage.getItem('title'))
      this.titleService.setTitle(localStorage.getItem('title'));
    else this.titleService.setTitle('No title');
  }
}

这是一个现场应用

代码- 斯塔克布利茨

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70334660

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档