FCC Speedrun — Random Quote Machine

P1xt
P1xt’s Blog
Published in
2 min readMar 8, 2017

The Random Quote machine is the second project I elected to complete in the Chingu FCC Speedrun Challenge speed run. I considered going in “FCC order” but it makes sense (to me at least) to not tackle the portfolio until I actually have something to put in it.

This project was interesting, much more so than the tribute page, I got to play around with how to get around CORS issues in order to consume an external API via an Angular 2 service.

Long story short, the trick to this is messing around with a plethora of APIs until you find one that will let you use jsonp. Our winner: forismatic.

Once you’ve picked an appropriate API, setting up a service to retrieve a quote is as simple as this:

import { Injectable }    from '@angular/core';
import { Http, Response, Jsonp, URLSearchParams } from '@angular/http';

@Injectable()
export class QuotesApiService {

constructor(private jsonp: Jsonp) { }

getQuote = () => {
let apiUrl: string = 'http://api.forismatic.com/api/1.0/';
let params = new URLSearchParams();
params.set('method', 'getQuote');
params.set('format', 'jsonp');
params.set('key', '457653');
params.set('lang', 'en');
params.set('jsonp', 'JSONP_CALLBACK');
return this.jsonp
.get(apiUrl, { search: params })
.map(response => response.json());
}
}

Then, you can just inject your service into whichever components need it and then subscribe to the data in a function you call from your click handlers:

constructor (private quotesApiService: QuotesApiService) { }
ngOnInit() {}
getQuote(term: string) {
this.quotesApiService.getQuote()
.subscribe(quotes => this.quote = quotes );
}

I worked through a couple of the issues I had on the tribute page and integrated the solutions into my random quote machine. Namely:

  • to make the favicon work in both dev and prod, put it in assets and change the link in index.html to grab it from there
  • there is some extra importing and declarations you have to do to make using Material Design components not break the default tests — I wrote a brief post about it.

The final result:

Notes:

Notes for me:

  • Start implementing more robust tests in some of the projects
  • Continue thinking about CSS naming conventions

For anyone who’s interested — here’s the mockup I threw together in Pencil at the start and was working towards:

My progress in the Speedrun thusfar:

Until next time — happy coding

--

--