我有一个使用angular Universal的网站。为了提高我的网站的搜索引擎优化,我希望用API动态下载我的页面标题。
问题是我的请求AJAX在服务器呈现之后工作。
下面是我的组件的代码:
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});
}
);
下面是我的服务代码:
getSeo (subdomain){
return this.http.get('https://url/api/'+ subdomain + '/seo')
.map((response: Response) => {
return response.json();
});
}
发布于 2018-04-20 22:11:15
我不能完全理解您的问题,但是您可以使用isPlatformServer和isPlatformBrowser方法分别在服务器端或客户端执行特定的任务。
在angular universal中,当你服务调用api时,api在服务器端渲染甚至在客户端浏览器上都会被点击两次,因此你可以使用TransferState方法来最小化服务器端的调用,并在数据到达浏览器之前获取数据。
代码的变通工作可以是。
1)在类之前为你的标题创建一个masterStateKey,并在你的构造函数中创建一个私有的transferstate变量。
2)使用masterstatekey调用接口,只命中服务端,并使用isPlatformServer方法初始化您的title变量。
示例:-
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);
}
https://stackoverflow.com/questions/48816833
复制相似问题