I am using Google DFA (gpt.js) in Angular.
The first time an ad is displaying fine but second time it gives null error.
I have directive which has the following method, called in OnInit
method:
addGoogleAd() {
const googletag: any = window['googletag'] || {};
if (window['googletag'] && googletag.apiReady) {
googletag.cmd = googletag.cmd || [];
googletag.cmd.push(() => {
googletag.pubads().setTargeting('site', 'weatherinnovations');
googletag.pubads().enableSingleRequest();
googletag.defineSlot('/xx/weather_innovations', [[160, 600]], 'div-gpt-ad-xx-1')
.setTargeting('position', ['s1']).addService(googletag.pubads());
googletag.defineSlot('/xx/weather_innovations', [[300, 250]], 'div-gpt-ad-xx-2')
.setTargeting('position', ['s2']).addService(googletag.pubads());
googletag.defineSlot('/xx/weather_innovations', [[300, 250]], 'div-gpt-ad-xx-3')
.setTargeting('position', ['s3']).addService(googletag.pubads());
googletag.defineSlot('/76643716/weather_innovations', [[728, 90]], 'div-gpt-ad-xx-4')
.setTargeting('position', ['s4']).addService(googletag.pubads());
googletag.defineSlot('/xx/weather_innovations', [[728, 90]], 'div-gpt-ad-xx-5')
.setTargeting('position', ['s5']).addService(googletag.pubads());
googletag.pubads().collapseEmptyDivs(true, true);
googletag.enableServices();
});
googletag.display(this.id);
}
}
The dashboard loads and displays ad, but when I return back from another component it gives the following error:
pubads_impl_265.js:1 Exception in queued GPT command TypeError: Cannot read property 'setTargeting' of null
I consoled the googletag
and is not empty, and has same content.
The error was not descriptive to debug it fast. Now, I am destroying the previously created slots before creating more and this solved the problem. Use the line right before googletag.cmd.push
googletag.destroySlots();