我设置了一个Angular CLI -v6.0.0项目,并使用此链接Angular Universal从服务器端呈现。我的整个项目都是从服务器端成功渲染的。演示链接在MyUniversalDemo。
当我点击产品进入产品详细信息页面时,标题和元信息正在更新,我在源视图中发现它是我使用静态数据时的期望。
但问题是当我尝试使用http请求从后端获取数据来更新标题和元信息时,标题和元信息不会更新。
我的SEO内容更新服务:
import { Injectable, Inject } from '@angular/core';
import { Title, Meta } from '@angular/platform-browser';
@Injectable()
export class SeoContentLoaderService {
constructor(private titleService: Title, private metaService: Meta) { }
setContent(title: string, description: string, keywords: string, slug: string = '', image: string = '', update = true) {
let tags = {
title: title && title != '' && update ? title : "Boibazar Largest Online Book Store in Bangladesh",
description: description && description != '' && update ? description : "Buy Books & Get Home Delivery anywhere in Bangladesh",
keywords: keywords && keywords != '' && update ? keywords : "Books, Boibazar, Boimela, Book, Bangladesh, Largest, Big, Boro, Bishal, Online, Shop, Place",
image: image
}
this.titleService.setTitle(tags.title);
this.metaService.updateTag({ name: 'twitter:card', content: 'Product' });
this.metaService.updateTag({ name: 'twitter:site', content: 'Boibazar.com' });
this.metaService.updateTag({ name: 'twitter:title', content: tags.title });
this.metaService.updateTag({ name: 'twitter:description', content: tags.description });
this.metaService.updateTag({ name: 'twitter:image', content: `http://118.179.223.38:8081/${tags.image}` });
this.metaService.updateTag({ property: 'og:type', content: 'Product' });
this.metaService.updateTag({ property: 'og:site_name', content: 'Boibazar.com' });
this.metaService.updateTag({ property: 'og:title', content: tags.title });
this.metaService.updateTag({ property: 'og:description', content: tags.description });
this.metaService.updateTag({ property: 'og:image', content: `http://118.179.223.38:8081/${tags.image}` });
this.metaService.updateTag({ property: 'og:url', content: `http://118.179.223.38:8081/book/${slug}` });
}
}
产品详细信息组件:
import { Component, ViewContainerRef } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ProductService, SeoContentLoaderService } from'../shared/services';
@Component({
selector: 'product-detail',
templateUrl: './product.details.html',
styleUrls: ['./product.details.scss'],
encapsulation: ViewEncapsulation.None
})
export class ProductDetailComponent {
public product: any = {};
constructor(
private seoContentLoaderService: SeoContentLoaderService,
private route: ActivatedRoute,
public productService: ProductService){}
ngOnInit() {
let slug=this.route.snapshot.params['slug'];
this.productService.get(slug).subscribe((result) => {
this.product = result.product;
this.seoContentLoaderService.setContent(
this.product.name, this.product.meta_tag_description,
this.product.meta_tag_keywords, slug, this.product.image
);
})
}