web-dev-qa-db-ja.com

Angular 2コンポーネントのGoogleAdSense広告?

アプリのAdComponentにレスポンシブ広告を読み込もうとしています。コンポーネントは非常に単純です。

import { Component } from '@angular/core';
import { FORM_DIRECTIVES, CORE_DIRECTIVES } from '@angular/common';

@Component({
  selector: 'ad',
  templateUrl: 'app/views/ad.html',
  directives: [ FORM_DIRECTIVES, CORE_DIRECTIVES ]
})
export class AdComponent {}

ad.html

<div class="demo-card-wide mdl-card mdl-shadow--2dp ad-card">
  <div class="mdl-card__supporting-text">
    <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
    <ins class="adsbygoogle"
        style="display:block"
        data-ad-client="ca-pub-0123456789"
        data-ad-slot="0123456789"
        data-ad-format="rectangle, horizontal"></ins>
    <script>
    (adsbygoogle = window.adsbygoogle || []).Push({});
    </script>
  </div>
</div>

これらのスクリプトタグがUIに反映されないことがわかりました。 これは意図的な決定のようです

Js参照などの一部のコードをindex.htmlの先頭に移動したり、window.adsbygoogle部分をコンポーネントコンストラクターに移動したりできる場合がありますが、これらの種類の変更が許可されているかどうかはわかりません。これらの広告をAngular 2で機能させるためのより良い代替手段がある場合。

誰かがAngular 2で動作するGoogleのAdSense広告の経験がありますか?これを行うための別の適切な方法はありますか?

11
Corey Ogburn

これは私のために働いています:

TopBannerComponent.ts ==>

    import {Component,OnInit,AfterViewInit} from '@angular/core'

    @Component({
      moduleId: module.id,
      selector: 'google-adsense',
      template: ` <div>
            <ins class="adsbygoogle"
                style="display:block"
                data-ad-client="ca-pub-0443011292983797"
                data-ad-slot="8184819393"
                data-ad-format="auto"></ins>
             </div>   
                <br>            
      `,

    })

    export class TopBannerComponent implements AfterViewInit {

      constructor() {    
      } 

      ngAfterViewInit() {
         setTimeout(()=>{
          try{
            (window['adsbygoogle'] = window['adsbygoogle'] || []).Push({});
          }catch(e){
            console.error("error");
          }
        },2000);
     }     
    }

広告を表示するHTMLにこれを追加します

<google-adsense></google-adsense>

あなたのメインのhtmlファイルにグーグルアドセンススクリプトを追加します

 <script async src=//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js></script>
12
Maayan Hope

私にとって非常にうまく機能するモジュールがあります: ng2-adsense

これを使用することを選択した場合、HTMLコードは次のようになります。

<ng2-adsense
  [adClient]="'ca-pub-7640562161899788'"
  [adSlot]="7259870550">
</ng2-adsense>

モジュールをインストールしたら、モジュールをインポートしてNgModuleに追加する必要があります。

import { AdsenseModule } from 'ng2-adsense';
@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    AdsenseModule, // <--- Add to imports
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

そして、この標準のAdSenseコードをindex.htmlに追加します。

<script async src=//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js></script>
4
Nir