除了产权服务之外, 图像、描述和关键字元不会显示在任何检查器上,即使它们出现在 dom 中也不起作用 我正在使用 Angular 13.0.2 并让元数据动态地来自 API 调用。 虽然我可以理解为什么它们没有出现在页面源代码中,但感觉我无能为力,因为元服务没有像预期的那样工作,我不确定我做得是否正确。 我也尝试使用 updateTag 而不是 addTag 无济于事。
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { DataServiceService } from 'src/data-service.service';
import { TranslateService } from '@ngx-translate/core';
import { Title, Meta } from '@angular/platform-browser';
import { TemplateChildComponent } from '../template-child/template-child.component';
@Component({
selector: 'app-template-page',
templateUrl: './template-page.component.html',
styleUrls: ['./template-page.component.css'],
entryComponents: [TemplateChildComponent],
encapsulation: ViewEncapsulation.None
})
export class TemplatePageComponent implements OnInit {
public pageData: any = {};
public meta: {
id: any,
title: any,
description: any,
keywords: any,
image: any,
} = null;
public components: any[] = [];
constructor(
private dataService: DataServiceService,
private route: ActivatedRoute,
private titleService: Title,
private metaService: Meta,
public translate: TranslateService
) {
translate.addLangs(['el', 'en']);
//translate.setDefaultLang('el');
}
public keywords: string[];
ngOnInit() {
this.route.params.subscribe(params => {
let id = params['id'];
let type = params['type'];
this.getData(id, type);
});
}
getData(idName: string, type ? : string) {
if (type === "page") {
this.dataService.getStaticPage(idName).subscribe(result => {
this.pageData = result;
this.meta = result.meta;
this.components = result.components;
console.log("pageData", this.pageData)
console.log("components", this.components)
this.titleService.setTitle(this.meta.title[this.translate.currentLang]);
this.keywords = this.meta.keywords.map(keyword => keyword[this.translate.currentLang]);
const keywordsContent = this.keywords.filter(keyword => keyword).join(', ');
this.metaService.addTag({
name: 'description',
content: this.meta.description[this.translate.currentLang]
});
this.metaService.addTag({
name: 'keywords',
content: keywordsContent
});
this.metaService.addTag({
property: 'og:image',
content: this.meta.image
});
});
} else {
this.dataService.getAnnouncementById(idName).subscribe(result => {
this.pageData = result;
this.meta = result.meta;
this.components = result.components;
console.log("pageData", this.pageData)
console.log("components", this.components)
this.titleService.setTitle(this.meta.title[this.translate.currentLang]);
this.metaService.addTag({
name: 'description',
content: this.meta.description[this.translate.currentLang]
});
});
}
}
}
除非您通过 Angular Universal 通过 SSR 或 SSG(静态预渲染)进行操作,否则它将无法工作。