Angular universal dynamic title
I have a website using angular Universal. To improve the seo of my website, I wish to dynamically download the titles of my pages with an API.
The problem is that my request AJAX works after server rendering.
Here is the code of my component:
this.seoService.getSeo(this.subdomain).subscribe(
seo => {
this.seo = seo;
this.titleService.setTitle(this.seo.menu_title );
this.metaService.addTag({name: 'description', content: this.seo.menu_description});
}
);
Here is the code of my service:
getSeo (subdomain){
return this.http.get('https://url/api/'+ subdomain + '/seo')
.map((response: Response) => {
return response.json();
});
}
I am not able to fully understand your problem, but you can use isPlatformServer and isPlatformBrowser method to perform particular task on server side or client side respectively.
In angular universal when you service call an api, the api is hit twice on server side rendering and even on client browser for that you can use TransferState method to minimise the call on server side and get the data before it comes to the browser.
the work around for your code can be.
1) Create a masterStateKey for your title before the class and create a private transferstate variable in your constructor.
2) Call the api using masterstatekey so that it is hit only server side and initialise your title variable using isPlatformServer method.
example:-
const RESULT_KEY = makeStateKey('result');
ngOnInit() {
this.test = this.state.get(RESULT_KEY, null as any);
if (!this.test) {
this.http.get('http://127.0.0.1:8080/api/test')
.subscribe( result => {
this.test = result;
this.state.set(RESULT_KEY, result);
});
}
console.log(this.test);
}
链接地址: http://www.djcxy.com/p/31308.html
上一篇: 以字符串形式呈现视图
下一篇: 有角度的通用动态标题