Angular 4在Meta标签上呈现

时间:2017-07-30 08:37:00

标签: javascript angular

呈现Meta标签时是否触发了事件?

在我的角度4应用程序中,我有一些动态路线,如:

const routes: Routes = [
  { path: 'products/:slug', component: ProductComponent }
];

在ProductComponent(product.component.ts)中,我得到如下的元数据:

ngOnInit() {
    let currentSlug = this.route.snapshot.paramMap.get('slug');

    //Makes ajax call to server to get meta data
    this.MyMetaService.getMeta(currentSlug)
        .subscribe((metadata) = > {
          //Set the page title
          this.title.setTitle(metadata.title);

          this.meta.addTags([
            {name: 'keywords', content: metadata.keywords},
            {name: 'description', content: metadata.description}
        ])
      });
  }

哪个工作正常!现在,我想知道元标记何时在页面上完全呈现,但到目前为止还无法弄清楚如何!

我尝试了以下但失败了:

ngAfterViewInit() {
    const title = $(document).find("title").text();
    console.log('page title is: ', title); //title is still not updated!
  }

当然setTimeout有效,但我不确定它不可靠:

setTimeout(() => {
    const title = $(document).find("title").text();
    console.log('page title is: ', title); //Got correct title here!
}, 200);

1 个答案:

答案 0 :(得分:0)

这背后的原因是,您正在进行ajax调用以检索元标记,这需要时间从服务器进行往返(可能只有几毫秒)。一旦内部组件树被渲染,就会调用ngAfterViewInit组件钩子。

我不这么认为setTimeout让它独立工作,因为你提到200ms时间,所以工作正常。

相关问题