Angular Universal 5 - Meta Service not working

馋奶兔 提交于 2020-01-06 06:58:23

问题


I had my meta tags working for Facebook and Twitter but I've somehow broken them. I looked at examples, but I can't see the issue. (There are no errors.) The tags just don't change from the defaults in index.html. I'm using Angular Universal 5.

Unlike the examples I found, I'm not writing the tags in the constructor. Not sure if that's a factor. I must be missing some rule of using the Meta service. Here's the code...

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

    constructor( ... private metaService: Meta ... ) {}

    ngOnInit () { 
    ...  

        // <!-- Facebook meta data -->
        this.metaService.addTags([
         {property: 'og:title', content: 'test' },
         {property: 'og:url', content: 'url' },
        ]);
        // <!-- Twitter meta data -->
        this.metaService.addTag({name: 'twitter:title', content: 'test });
   ...
   }

回答1:


If the tags are already there, you need to use updateTag instead of addTag

Looking at the source code, addTag does not add the meta tag if it's already present in the dom (like in index.html)

https://github.com/angular/angular/blob/master/packages/platform-browser/src/browser/meta.ts

Note updateTag does add the meta to the dom if it does not already exists




回答2:


As @David suggested, switching from addTag (and addTags) to updateTag fixed the issue.



来源:https://stackoverflow.com/questions/49623950/angular-universal-5-meta-service-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!