在我的 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');
}
标题和标签在检查元素中更新,但不在查看页面源代码中更新。
如有任何建议,我们将不胜感激。
您的
if (isPlatformBrowser(this.platformId))
条件意味着之后的代码仅在客户端执行,而不是在执行SSR时执行。 view-source中显示的代码是SSR生成的代码。
您需要删除该条件。而且,
getData
使用universal时必须调用绝对url
我认为你可以使用这个模块 - ngx-meta
https://www.npmjs.com/package/@ngx-meta/core
然后,在您的 api 调用中使用它 - this.title.setTitle(res.name);
如果 api 调用有 http 请求,请使用解析器,在路由导航之前渲染标题会更加复杂,通过使用解析防护,您可以在路由导航之前获取标题,因此 SSR 将帮助在渲染页面之前设置标题通过实现此功能,您可以在查看页面源代码中获得更新的标题!您在检查元素中观察到的更新标题是渲染页面后更新的标题