Angular 通用:标题和元标记未在页面源中更新
Angular Universal: Title and meta tags and not updated in Page Source
在我的 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);
在我的 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
我想你可以使用这个模块 - ngx-meta
https://www.npmjs.com/package/@ngx-meta/core
然后,在您的 api 调用中使用它 - this.title.setTitle(res.name);