2017-05-03 21 views
0

我有一個需要動態元數據搜索引擎優化的angular4博客應用程序。 我的服務(BlogService)從PHP服務器提供JSON數據。 例如如何在Angular4中添加動態元數據

{"ID":"168","title":"HTML Src Test","description":"testing the html thingy in angular","content":"<h1>Hello, World ... This is a heading.<\/h1>\n<p><img title=\"test\" src=\"https:\/\/i.stack.imgur.com\/ipOIT.png\" alt=\"test\" width=\"20%\" \/><\/p>\n<pre class=\"prettyprint\">code code <br \/>function(){<br \/>console.log(\"hello\");<br \/>alert(\"hello\");<br \/>}<\/pre>\n<p>&nbsp;<\/p>","date":"26th Apr 2017","slug":"html-src-test","imagepath":"","category":"Testy Test McTest","ttr":1,"comcount":0} 

這然後解釋和顯示的以通常的方式角(例如 {{post.title}})

BlogService:

getPost(slug: string): Promise<Post> { 
     const url = `${this.blogUrl}?id=${slug}`; 
     console.log(this.http.get(url).toPromise().then(response => response.json())); 

     return this.http.get(url) 
      .toPromise() 
      .then(response => response.json() as Post) 
      .catch(this.handleError); 
    } 

BlogpostComponent:

ngOnInit(): void { 
    this.getData(); 
} 
getData() { 
    this.route.params 
     .switchMap((params: Params) => this.service.getPost(params['slug'])) 
     .subscribe(post => this.post = post); 
} 

如何從此HTTP請求傳遞數據並將其顯示在HTML中的元標記中?

感謝

+0

隨着谷歌開始關注頁面內的實際內容,而不是元標記標題和描述,元標記已經不再重要了(豁免必須)。只要確保頁面中有良好的鏈接和內容,並確保您的網址不吸吮,並且可讀。除此之外,安圭爾宇宙應該照顧其餘的。 – EyoelD

回答

1

這是假設,我們意識到這意味着什麼對SEO沒有universal(服務器端渲染)等,並且還,我們使用的是V4 +。

您可以處理平臺的瀏覽器,具有TitleMeta元等

import { Title, Meta, MetaDefinition } from '@angular/platform-browser'; 
... 

constructor(
    private _meta: Meta, 
    private _title: Title 

... 

this._title.setTitle('foo'); 

... 

let meta: MetaDefinition[] = [ 
    { name: 'application-name', content: 'foo' }, 
    { name: 'description', content: 'bar' } 
]; 

this._meta.addTags(meta); 

更新: 所以,是的,你的情況,你可以添加一個基於響應。

.subscribe((post) => { 
    this.post = post; 
    this._title.setTitle(this.post.title); 
}); 

對於清潔度我會創建一個單獨的「service.method」喜歡「setPageMeta()」,其可以被用來處理route.data或HTTP響應。

+0

感謝上述, 我如何將數據從組件傳遞到元數據? 「this.post.title」是否工作(或類似)? –

+0

我只是把相關的位,你會添加方法/事件(如路由器/ navigationEnd)或當一些數據返回。您將需要搜索控制檯中的元素進行驗證。 – Dylan