【问题标题】:Angular Universal: Title and meta tags and not updated in Page SourceAngular Universal:标题和元标记,未在页面源中更新
【发布时间】:2021-04-30 09:56:35
【问题描述】:

在我的 Angular 通用应用程序中,我尝试在 api 调用成功后更新标题和元标记。

app.component.ts

import {Component, Inject, OnInit, PLATFORM_ID} from '@angular/core';
import {Meta, Title} from '@angular/platform-browser';
import {isPlatformBrowser} from '@angular/common';
import {TestService} from './test.service';

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

  constructor(private testService: TestService,
              private title: Title,
              private meta: Meta,
              @Inject(PLATFORM_ID) private platformId: Object) {
  }

  ngOnInit(): void {
    if (isPlatformBrowser(this.platformId)) {
      this.testService.getData().subscribe((res: any) => {
        console.log(res);
        this.title.setTitle(res.name);
        this.meta.updateTag({property: 'og:title', content: res.name});
      });
    }
  }
}

在服务中...

  getData() {
    return this.http.get('assets/data.json');
  }

标题和标签在检查元素中更新,但不在查看页面源中。

欢迎提出任何建议。

【问题讨论】:

    标签: angular angular-universal


    【解决方案1】:

    您的if (isPlatformBrowser(this.platformId)) 条件意味着之后的代码仅在客户端执行,而不是在执行 SSR 时。 view-source中显示的代码是SSR生成的代码。

    您需要删除该条件。而且getData在使用universal时必须调用绝对url

    【讨论】:

    • 这怎么可能?没有 if (isPlatformBrowser(this.platformId)),我们无法调用 localStorage 函数。
    • 好吧,做SSR的时候不要使用localStorage。
    • 那么,除了本地存储之外,保留用户令牌的最佳方法是什么?
    • 你必须使用cookies
    【解决方案2】:

    我认为你可以使用这个模块 - ngx-meta

    https://www.npmjs.com/package/@ngx-meta/core

    然后,在您的 api 调用中使用它 - this.title.setTitle(res.name);

    【讨论】:

      猜你喜欢
      • 2022-11-04
      • 1970-01-01
      • 2019-03-16
      • 2021-04-12
      • 1970-01-01
      • 1970-01-01
      • 2021-09-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多