Angular random quote #3

This is the third project of my ongoing challenge, 100 angular projects.

In this project, I created a web page which fetches a random quote from an API endpoint and displays it on the page.

Screen Shot Muse

I have learned a few new concepts while creating this simple web application, such as

  • using services to separate fetching data from components
  • using observable and Angular HttpClient for fetching data asynchronously and providing a way for the data to be consumed from a component
  • calling child component’s function from parent component using @ViewChild

Service, Observable and HttpClient for asynchronous API call

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
providedIn: 'root'
export class QuoteService {
private quoteUrl = "";
getQuote(): Observable <{}> {
return this.http.get(this.quoteUrl)
private http: HttpClient
) { }

view raw
hosted with ❤ by GitHub

Using service to get a random quote from a component

import { Component, OnInit } from '@angular/core';
import { QuoteService } from '../quote.service';
selector: 'app-random-quote',
templateUrl: './random-quote.component.html',
styleUrls: ['./random-quote.component.css']
export class RandomQuoteComponent implements OnInit {
constructor(private quoteService: QuoteService) { }
getQuote(): void {
.subscribe(quote => {
this.quote = '"' + quote['quote'] + '"'; = '~' + quote['author']
quote: string;
author: string;
ngOnInit() {

Calling child component’s function from the parent component

import { Component, ViewChild } from '@angular/core';
import { RandomQuoteComponent } from './random-quote/random-quote.component'
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
export class AppComponent {
private randomQuoteComponent: RandomQuoteComponent;
title = 'Muse';
onClickMe() {

view raw
hosted with ❤ by GitHub

Live address:



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s