Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

Famous Quotes – Ionic example apps

Ionic Capacitor is an open-source framework innovation to help you build Progressive Native Web, Mobile, and Desktop apps. In these articles, we create an ionic example app called famous quotes to display list of quotes. We are building quotes apps, our apps by default will display all the quotes from one JSON file and we can type to find quotes from a particular author.

What are we learning?

  1. We will fetch or read a JSON file containing all quotes in quotes.ts.
  2. Sharing the quotes on social networking twitter through Cordova-plugin-x-socialsharing.
  3. Passing quote between different page using service.
  4.  We have control of the search through the quote.

Let’s build the apps, following all the steps as 

Step 1: Creating the apps through blank template and adding one more page as

$ionic start quoteApp blank --type=angular
$ionic generate page quote
Add socila sharing plugin
$ionic cordova plugin add cordova-plugin-x-socialsharing
$npm install @ionic-native/social-sharing

Step 2: Add folder data in the assets folder and create a new file quotes.json where we add all quotes. Format of our quotes.JSON assets/data/quotes.json as

{
  "quotes": [
    { 
      "quote": "Believe nothing, no matter where you read it, or who said it, no matter if I have said it, unless it agrees with your own reason and your own common sense.",
      "author": "Buddha"
    },
    { 
      "quote": "What you think, you become. What you feel, you attract. What you imagine, you create",
      "author": "Buddha"
    },
    { 
      "quote": "To whomever emptiness is possible, all things are possible.",
      "author": "Nāgārjuna"
    },
    {
      "quote": "The goal is not to be better than the other man, but your previous self.",
      "author": "Dalai Lama"
    },
    {
      "quote": "Happiness is not something ready made. It comes from your own actions.",
      "author": "Dalai Lama"
    },
    {
      "quote": "The ultimate authority must always rest with the individual’s own reason and critical analysis.",
      "author": "Dalai Lama"
    },
    {
      "quote": "Happiness is not something ready made. It comes from your own actions.",
      "author": "Dalai Lama"
    }

  ]
}

and we also need to add the social sharing reference in provider in app.modules.ts

import { NgModule } from '@angular/core';
....
import { AppRoutingModule } from './app-routing.module';
import { SocialSharing } from '@ionic-native/social-sharing/ngx';
@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    SocialSharing
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Step 3: We will use fetch() function to read the JSON file to home.page.ts file. The fetch() method allows you to make network requests similar to XMLHttpRequest (XHR). The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API, avoiding callback hell and having to remember the complex API of XMLHttpRequest. Add the following code in home.page.ts file to read JSON data from quote.json

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { QuoteService } from '../../services/quote.service';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  quotes: [];
  filteredQuotes = [];
  isfiltered = false;

  constructor(
    private router: Router,
    private quoteService: QuoteService,
  ) { }

  ionViewWillEnter() {
    fetch('./assets/data/quotes.json').then(res => res.json())
      .then(json => {
        this.quotes = json.quotes;
      });
  }

  searchQuotes(event) {
    if (event.target.value.length > 2) {
      const filteredJson = this.quotes.filter((row: any) => {
        const str = event.target.value.toLowerCase();
        row.author = row.author.toLowerCase();
        if (row.author.indexOf(str) !== -1) {
          return true;
        } else {
          return false;
        }
      });
      this.isfiltered = true;
      this.filteredQuotes = filteredJson;
    }
  }

  getQuoteDetail(quote) {
    this.quoteService.setQuote(quote);
    this.router.navigate(['/quote']);
  }
}

Note: The quote is the variable defined to contain the JSON object. filteredQuotes is the variable that will contain the search results. When we click on any one quote, we will navigate to the quote page with a full quote with author information that will allow us to share it with twitter.

Step 4: Adding the search result, now we will add the search bar to the search quote through the author name.  Add the following code in home.html

<ion-header>
  <ion-toolbar>
    <ion-title>
      Quote Application
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <div class="ion-padding">
    <ion-input type="text" placeholder="Search Quotes..." (input)="searchQuotes($event)"></ion-input>

    <ion-list *ngIf="!isfiltered">
      <ion-item *ngFor="let quote of quotes" (click)="getQuoteDetail(quote)">
        <ion-text color="primary">
          <h4>{{quote.author}}</h4>
        </ion-text>
        <p>{{quote.quote}}</p>
      </ion-item>
    </ion-list>

    <ion-list *ngIf="isfiltered">
      <ion-item *ngFor="let quote1 of filteredQuotes" (click)="getQuoteDetail(quote1)">
        <p>{{quote1.quote}}</p>
        <h2>{{quote1.author}}</h2>
      </ion-item>
    </ion-list>
  </div>
</ion-content>

The search box when we type more than 2 characters, searchQuotes() is called for searching the JSON object, it will filter the quotes from the quotes variable. The first ion-list is displayed when the isfiltered value is false, to display the entire list of quotes. The second ion-list is displayed when the isfiltered value is true, to display only the filtered list of quotes.

Step 5: In Ionic 3 is mostly focused on mobile applications where we can use NavController to send object data between pages but this is not the case where Ionic 4 and above latest 5 are web component-based where we will use services or provider to pass data between pages. Create folder services in the src or root folder and create a file called quote.service.ts where we used to set and get a function to pass quote between pages. Add following code in src/services/quote.service.ts

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

@Injectable({
  providedIn: 'root'
})
export class QuoteService {
  quote: any;

  constructor() { }

  setQuote(quote) {
    this.quote = quote;
  }

  getQuote() {
    return this.quote;
  }
}

Add the following code in  quote.page.html, here we are displaying the quote author and quote in detail and clicking on share twitter will call twitterShare() method to share on twitter apps.

<ion-header>
  <ion-toolbar>
    <ion-title>Quote</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <div *ngIf="quote" class="ion-padding">
    <ion-item (click)="twitterShare()">
      <p>{{quote.quote}}</p>
      <h4> - {{quote.author}}</h4>
    </ion-item>
  </div>
</ion-content>

Add the following code in pages/quotes.ts, we are retrieving quote detail and sharing social networking, in our case we have use twitter, you can use Facebook, Instagram, SMS, and many more.

import { Component } from '@angular/core';
import { SocialSharing } from '@ionic-native/social-sharing/ngx';
import { QuoteService } from 'src/services/quote.service';

@Component({
  selector: 'app-quote',
  templateUrl: './quote.page.html',
  styleUrls: ['./quote.page.scss'],
})
export class QuotePage {
  quote;

  constructor(
    private socialSharing: SocialSharing,
    private quoteService: QuoteService) { }

  ionViewWillEnter() {
    this.quote = this.quoteService.getQuote();
  }

  twitterShare() {
    const msg = this.quote.quote;
    this.socialSharing.shareViaTwitter(msg.substring(0, 110) + '..', null, 'http://ionicframework.com/img/homepage/ionicview-icon_2x.png')
      .then((data) => {
        alert('Success ' + data);
      },
        (err) => {
          alert('failed ' + err);
        });
  }

}

Step 6:  We have to add quote.service.ts reference file in provider in app.module.ts

import { NgModule } from '@angular/core';
.....
import { SocialSharing } from '@ionic-native/social-sharing/ngx';
import { QuoteService } from '../services/quote.service';
@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    SocialSharing,
    QuoteService
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}
Famous Quotes – Ionic example apps

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top