Update meta tags in angular universal with external API call

后端 未结 4 1991
庸人自扰
庸人自扰 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:28

    Couldn't find an easy way to do it but here's a temporary/hacky solution provided by a GitHub user here and I'm quoting his answer directly:

    //all imports
    enableProdMode();
    
    export const app = express();
    
    const mysql = require('mysql');
    const httpRequest = require("request");
    // all other consts
    
    app.engine('html', ngExpressEngine({
      bootstrap: AppServerModuleNgFactory,
      providers: [
        provideModuleMap(LAZY_MODULE_MAP)
      ]
    }));
    //all other piece of code in server.ts
    
    app.get('/*', (req, res) => {
      res.render('index', {req, res}, (err, html) => {
        if (html) {
            
            //console.log(html);
            // This is where you get hold of HTML which "is about to be rendered"
        
            // after some conditional checks make a HTTP call
            let url = 'http://....';
            httpRequest.get(url, (error, response, body) => {
                            if(error) {
                                return console.log(error);
                            }
                            const respBody = JSON.parse(body);
                            if(respBody){
                                  html = html.replace(/\$TITLE/g, respBody.title);
                                  html = html.replace(/\$DESCRIPTION/g, respBody.description);
                                  html = html.replace(/\$OG_META_KEYWORDS/g, respBody.metaKeywords);
                                  html = html.replace(/\$OG_META_DESCRIPTION/g, respBody.metaDescription);
                                  html = html.replace(/\$OG_DESCRIPTION/g, respBody.ogDescription);
                                  html = html.replace(/\$OG_TITLE/g, respBody.ogTitle);
                                  html = html.replace(/\$OG_IMAGE/g, respBody.img);
                                  html = html.replace(/\$OG_SITE/g, respBody.ogSite);
                            }
                            res.send(html);
                });
         }
      }
    }
    

    And in index.html, create template values as below:

        $TITLE
    
         
        
         
        
        
        
         
           
        
    

提交回复
热议问题