refresh the google ads (adsense) on angular route change

784 views Asked by At

i m unable to refresh the google adsense on route change on layout component here is my app-routing modue

  //app-routing-module
  {
    path: '',
    component: LayoutComponent,
    children: [
      {
        path: '',
        loadChildren: () => import('./pages/pages.module').then(m => m.PagesModule)
      }
    ]
  },

here is pages-routing module

const routes: Routes = [
  {
    path: '',
    component: HomeComponent,
  },

google ad code is in separate banner component

  //banner component ts


  const navEndEvents = this.router.events.pipe(filter(event => event instanceof NavigationEnd))
    navEndEvents.subscribe((event: any) => {
      this.initGoogleAd();
    });
  private initGoogleAd() {
    try {
      (adsbygoogle = window.adsbygoogle || []).push({});

    } catch (e) { }
  }

banner component html

  <div>
    <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-6053771666988490"
                data-ad-slot="9396915897" data-ad-format="auto" data-full-width-responsive="true"></ins>
  </div>

Every thing works fine I m unable to rerender the google banner component on layout component

layout component

//..some other elements
  <app-banner></app-banner> //google ads not refreshing without reload
//..

Home component

..some other elements
  <app-banner></app-banner> //works on home component though
..

any help will be appreciated thanks

1

There are 1 answers

0
srijan lama On

temporarly solved with rxjs BehaviorSubject

// created BehaviorSubject in banner service

export class BannerService extends ApiService {
  bannerShow  = new BehaviorSubject<boolean>(true)
}

// emitted new value on NavigationEnd Observable of router within app component

navEndEvents.subscribe((event: any) => {
  this.bannerService.bannerShow.next(false)
  this.bannerService.all(3).subscribe((res: any) => {
    this.bannerService.bannerShow.next(true)
  });
});

// subscribed to bannerShow Observable with async pipe

//layout component ts
<app-banner *ngIf="bannerService.bannerShow | async"></app-banner>