在-Angular-网站部署-Google-广告

12次阅读

共计 1237 个字符,预计需要花费 4 分钟才能阅读完成。

原文地址:http://www.bowen-tech.top/art…

在 Angular 开发的网站部署 Google 广告

Google 广告代码是包含 script 代码的,如果直接复制 Google 广告到 Angular 的 html 页面上,编译时是会去除掉 script 标签代码,具体可看这个 GitHub 文章:传送门

新建 component

  • component 的 template 写上 google 广告的代码,不包含 script 标签的代码, 如下:
 template: `<div>
    <ins class="adsbygoogle"
         style="display:block"
         data-ad-client="ca-pub-xxxxxxx"
         data-ad-slot="xxxxx"
         data-ad-format="auto"
         data-full-width-responsive="true"></ins>
  </div>`
  • init 方法初始化 window.adsbygoogle
ngAfterViewInit() {
    try{(window['adsbygoogle'] = window['adsbygoogle'] || []).push({});
    }catch(e){console.error("error");
    }
  • 完整代码
import {Component, AfterViewInit} from '@angular/core';
// <!-- tools 网站纪念日计算横幅广告 -->
@Component({
  selector: 'app-commemoration-ad',
  template: `<div>
    <ins class="adsbygoogle"
         style="display:block"
         data-ad-client="ca-pub-xxxxxxx"
         data-ad-slot="xxxxx"
         data-ad-format="auto"
         data-full-width-responsive="true"></ins>
  </div>`
})
export class CommemorationAdComponent implements AfterViewInit {constructor() { }

  ngAfterViewInit() {
    try{(window['adsbygoogle'] = window['adsbygoogle'] || []).push({});
    }catch(e){console.error("error");
    }
  }

}

html 引入模块

<!-- 在您希望展示广告的 html 中添加此内容 -->
<app-commemoration-ad></app-commemoration-ad>

index.html 引入 js 文件

<script async=""src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

注意

如果是定义的公共模块,需要在模块里面申明

正文完
 0