Angular Universal 5 - Meta Service not working

2019-08-16 23:01发布

问题:

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.