问题
Is there any way to use Google Adsense ads on an Angular 2 app?
I have seen this Google AdSense ads in Angular 2 components? but the answer isn't actually working for me. I see a blank space instead of my ad. What I'm trying to place is responsive ad. I did exactly as the answer in the above question said, with this template code:
<div class="text-center">
<ins class="adsbygoogle" style="display:inline-block;height:150px"
data-ad-client="my ca-pub" data-ad-slot="my ad slot"></ins>
</div>
Any ideas?
回答1:
The answer in this link is worked for me. Even better I managed improve that code which can be use with dynamic Slot info.
banner.component.ts
import { Component, AfterViewInit, Input } from "@angular/core"
@Component({
moduleId: module.id,
selector: "google-adsense",
template: ` <div>
<ins class="adsbygoogle"
style="display:block;"
data-ad-client="write_your_pub_"
[attr.data-ad-slot]="data"
data-ad-format="auto"></ins>
</div>
<br>
`,
})
export class BannerComponent implements AfterViewInit {
@Input() data;
constructor() {}
ngAfterViewInit() {
setTimeout(() => {
try {
(window["adsbygoogle"] = window["adsbygoogle"] || []).push({});
} catch (e) {
console.error(e);
}
}, 2000);
} }
Add this in your html where you want your ad to appear
<google-adsense [data]="your_slot_id"></google-adsense>
Add google adsense script in your main html file
<script async src=//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js>/script>
Don't forget to add app.module.
In the other hand, Google adsense banners doesn't show in localserver and if it's in server it takes time to shown up. you can sure that it's working by changing backup ads property to
Fill space with a solid color
in Google Adsense portal.
回答2:
This may not be the best answer but I suggest using the module ng2-adsense. From there you can smoothly place the ad via using the HTML tag ng-adsense
.
来源:https://stackoverflow.com/questions/39372270/using-google-adsense-ads-on-angular-2-application