How to Use Pagespeed Insights API with Angular 5

Quick and Easy Angular 5 PageSpeed Service

Pagespeed Insights is a Google product that allows you to analyze a site for common hiccups that can cause a poor user experience. You can check it out at Google PageSpeed Insights. One of the problems with this is if you wanted to put it on your own site you would have to link back to Google, causing traffic to leave your site which you may never get back.

Luckily, Google offers a simple to use REST API that we can use to get the data and format it on our own sites. This way, you can show visitors to your site problems with their site while keeping your own site theme, your own branding, and without having to redirect traffic. While Google already has a tutorial, it is written for regular Javascript.

In this tutorial, I will show you how to setup the PageSpeed Insights API from within Angular 5. This will allow for a full component that can be placed anywhere on your site. We will make sure our data is in Observables as well to take full advantage of Angular's reactiveX.

Requirements

First, you need to make sure that you have a Angular installed. This guide was written with Angular 5 but the steps should be applicable to Angular 4+. For ease of use, I highly recommend using Angular-cli

Secondly, your are going to need to acquire an API key. This is required for many Google APIs and requires a Google account.

Once you have all these your ready to go.

Initial Setup

We are going to start by generating a new project using Angular-cli. We are going to generate a service in order to do our actual HTTP request.

Generating the Angular Project

Start by opening terminal. Navigate to the directory you want your project to be stored in.

cd ~/PATH/TO/DIRECTORY

Next using Angular-cli to generate a new Angular project.

ng new pagespeed-tutorial

Heads Up! Angular will look like it is stalled but it just takes a few minutes to install all the necessary components.

Now lets generate the service that we will need. We can do this easily with the Angular-cli again.

ng generate service PagespeedService

Import JsonpModule

We need to be able to get JSON-P data. To do this, we are going to use Angular's JsonpModule. Let's add this to the app.module.ts so we can use it.

Open the app.module.ts file, it should be located in the root of your src directory. Find the imports variable and add JsonpModule to it, it should look like this:

imports: [
JsonpModule
],

You will also have to make sure to import it by adding this to the top of app.module.ts with your other imports.

import { JsonpModule } from '@angular/http';

Add PagespeedService to Providers

Lastly, we need to add Pagespeed Service as a provider.

Import the Pagespeed Service by adding an import statement to the top of the app.module.ts

import { PagespeedService } from './pagespeed.service';

Near the bottom there will be a providers that will look like this:

providers: [],

Add in your PagespeedService by changing providers to

providers: [PagespeedService],

Now you should be all setup.

Pagespeed Service

The PageSpeed API takes in a URL, and returns JSON-P data back. Luckily, Angular makes these callbacks quite simple. Open the pagespeed.service.ts file. It should look like this:

import { Injectable } from '@angular/core';

@Injectable()
export class PagespeedService {

constructor() { }


}

Let's add two private variables to this, our API_KEY and the API_URL. Also, lets add Jsonp to our service using Angular's dependency injection.

import { Injectable } from '@angular/core';
import { Jsonp } from '@angular/http';

@Injectable()
export class PagespeedService {


private API_KEY = *INSERT YOUR API KEY HERE*;
private API_URL = 'https://www.googleapis.com/pagespeedonline/v2/runPagespeed';


constructor( private jsonp: Jsonp ) { }


}

Now, we will add the method that will call the PageSpeed API and return an Observable of the data. Our method requires a URL that will be supplied when the service is called from a component.

@Injectable()
export class PagespeedService {

private API_KEY = '*INSERT YOUR API KEY HERE*';
private API_URL = 'https://www.googleapis.com/pagespeedonline/v2/runPagespeed';

constructor( private jsonp: Jsonp ) { }

analyzePage(inputUrl) {
}

}

We will have just one line of code that will return the Observable. We're going to use the jsonp object and make a request. Jsonp's request method takes two arguments, a URL and a list of options.

return this.jsonp.request(this.API_URL, {
params: {'key': this.API_KEY, 'url': inputUrl, 'callback': 'JSONP_CALLBACK'}
});

All we did here was call the jsonp request method with the inputUrl. The options we are using are params to easily parse the params onto the url. We have the following params:

  • key: this is your Google PageSpeed API key
  • url: this is the url that PageSpeed should be run on
  • callback: Json-p data requires a callback function to bypass Cross-Origin Request issues. We use the Angular default JSONP_CALLBACK. This allows Angular to automatically get the data as it will rewrite the JSONP_CALLBACK param.
That's all with the service. As you can see this is much simpler than trying to accomplish this with plain Javascript and we have the added bonus of being reactive.

Conclusion

We just learned how to get back a Observable of Jsonp data. Now, we are just going to need a component that will utilize this. Stay tuned, in my next post I will show you how to create the component, give some ideas on how to style it, show how to plug the data into the Google Chart API, and finally how to pipe the data to allow for iteration.

See anything I could of done better? Feel free to share in the comments!

Comments

  1. Best Casino Sites 2021 | Top Casino Sites in Canada
    A list of 블랙 잭 the Best Casino Sites for 포커 룰 Canada 2021 · 1. 포커디펜스 Ignition · 2. PlayOJO · 포커 게임 3. Slots Empire · 4. Sloto Cash · 5. Wild Casino · 6. BigSpins · 7. Ignition Gaming · 스카이바카라 8.

    ReplyDelete
  2. Borgata Hotel Casino and Spa - Mapyro
    Hotel 안동 출장마사지 · Casino and Spa. 1 Borgata Way Atlantic City, NJ 08401 · 목포 출장안마 (609) 317-5000 · Visit Website. http://www.borgata.com · More Info. Hours, 삼척 출장샵 Accepts Credit Cards,  Rating: 5 · ‎1 vote · ‎Price range: 아산 출장샵 $ 전라북도 출장마사지

    ReplyDelete
  3. How do I make money from playing games and earning
    These gri-go.com are the three most popular forms of 바카라 사이트 gambling, and worrione.com are explained งานออนไลน์ in a very concise and concise manner. The most common poormansguidetocasinogambling forms of gambling are:

    ReplyDelete

Post a Comment