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.
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'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class QuoteService { | |
private quoteUrl = "https://talaikis.com/api/quotes/random/"; | |
getQuote(): Observable <{}> { | |
return this.http.get(this.quoteUrl) | |
}; | |
constructor( | |
private http: HttpClient | |
) { } | |
} |
Using service to get a random quote from a component
import { Component, OnInit } from '@angular/core'; | |
import { QuoteService } from '../quote.service'; | |
@Component({ | |
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 { | |
this.quoteService.getQuote() | |
.subscribe(quote => { | |
this.quote = '"' + quote['quote'] + '"'; | |
this.author = '~' + quote['author'] | |
}); | |
} | |
quote: string; | |
author: string; | |
ngOnInit() { | |
this.getQuote(); | |
} | |
} |
Calling child component’s function from the parent component
import { Component, ViewChild } from '@angular/core'; | |
import { RandomQuoteComponent } from './random-quote/random-quote.component' | |
@Component({ | |
selector: 'app-root', | |
templateUrl: './app.component.html', | |
styleUrls: ['./app.component.css'] | |
}) | |
export class AppComponent { | |
@ViewChild(RandomQuoteComponent) | |
private randomQuoteComponent: RandomQuoteComponent; | |
title = 'Muse'; | |
onClickMe() { | |
this.randomQuoteComponent.getQuote(); | |
} | |
} |
Live address: http://5b3705ca02ed8359970e2262.silly-perlman-68e0f4.netlify.com/
Git: https://github.com/zkkmin/muse