Update meta tags in angular universal with external API call

后端 未结 4 1993
庸人自扰
庸人自扰 2020-12-30 12:02

I\'ve spent more than 2 months but could not found a clear solution of how to proceed with angular universal. I\'ve already spent about 6 months in implementing angular univ

4条回答
  •  情书的邮戳
    2020-12-30 12:17

    Stumbled upon this looking for same solution. Using a setTimeout worked for me. Make sure to refresh cache or use incognito mode or you'll miss seeing the metadata (I made this mistake). My research suggests that subscribe for API data must be waited upon before SSR renders page so observable must stay open (but I'm not an expert). https://angular.io/guide/observables. Also, the only way to make it work is to put the response from subscription right into metaService. I'll show what I mean in my code.

    setTimeout( () =>
                  this.seo.setFromJson({
                  title: this.content.title,
                  image: this.content.main_image,
                  description: this.content.blog,
                  author: this.content.name,
                  keyword: ''
                });
        ,0);
    

    My code with solution:

    this.publicFeedService.getPublicProfile(data).subscribe((response:any) => {
            this.memberProfile = response[this.userId];
            setTimeout( () => 
            //Define the meta title using profile data
            this.titleService.setTitle('The best investment ideas from ' + response[this.userId].firstName + ' ' + response[this.userId].lastName), 0);
            setTimeout( () =>         
            //Define the meta tags using the user profile data
            this.metaService.addTags([
              {name: 'keywords', content: 'investing ideas, stock ideas, financial profile'},
              {name: 'description', content: response[this.userId].about},
              {name: 'robots', content: 'index, follow'}
            ]), 0);
    

提交回复
热议问题