Angular Universal 5 - Meta Service not working

2019-08-16 22:59发布

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 });
   ...
   }

2条回答
何必那么认真
2楼-- · 2019-08-16 23:22

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

查看更多
Luminary・发光体
3楼-- · 2019-08-16 23:23

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

查看更多
登录 后发表回答