Diccionario Multilenguaje en Ionic

diccionario-ionic

Proyecto que realizamos en Ionic que consume Dictionary Api para la búsqueda de palabras, soporta 12 idiomas, utilizamos Angular como framework para trabajar e incluimos varios componentes Ionic UI.

Creación del proyecto

Escogemos un proyecto tipo blank en la creación del proyecto

ionic start DiccionarioApp

Estructura del proyecto

Creamos las siguientes carpetas a nivel de app:

  • Components: Paquete que almacena los componentes de la aplicación
  • Models: Paquete que contiene las interfaces que sirven como modelo de clases.
  • Pages: Originalmente se crea una page llamada home, es muy diferente a un componente en el sentido de que una página tiene un modulo y su propio enrutamiento, esto con fines de utilizar lazy load
  • Services: Paquete que contiene el servicio para conectarse al api de Dictionary Api
Estructura-diccionario-app

La página home principal la pasamos al paquete pages, salta un error en app-routing.module.ts donde lo único que tenemos que cambiar es el import del home.module por ‘./pages/home/home.module’

En app.modulte.ts importamos HttpClientModule para el consumo de apis.

Creación de componentes

ng g c components/header
ng g s services/words
  • header: Cabecera de la aplicación.
  • words: Contenido de la aplicación.

Una vez creados los componentes nos dirigimos a pages/home/home.module.ts y agregamos en las declaraciones de esa pagina los componentes HeaderComponent y ContentComponent, ademas de importar ReactiveFormsModule

headerComponent

Creación del servicio

Antes de crear el servicio en el archivo enviroments vamos a colocar la URL base del endpoint que consumimos, esto es buena practica por temas de seguridad.

//enviroment.ts
export const environment = {
  production: false,
  baseUrl: 'https://api.dictionaryapi.dev/api/v2/entries'
};

Creamos el servicio:

ng g s services/words
//words.service.ts
import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class WordsService {

  baseUrl = environment.baseUrl;
  
  constructor(private http: HttpClient) { }

  getWord(language: string, word: string){
    return this.http.get(`${this.baseUrl}/${language}/${word}`);
  }
}

Creación de Modelos

export interface Definition {
    definition: string;
    example ?: string;
    synonyms: string[];
    class ?: string;
}
import { Definition } from './definition.model';

export interface Meaning {
    definitions: Definition[];
    partOfSpeech: string;
}

Header Component

<ion-toolbar>
  <ion-title>
    Diccionario App
  </ion-title>
</ion-toolbar>

Content Component

<ion-grid>
  <form [formGroup]="wordForm" (ngSubmit)="getWord()">
    <ion-row>
      <ion-col>
        <ion-item>
          <ion-label position="floating">
            <ion-icon name="search-outline"></ion-icon>
            Buscar
          </ion-label>
          <ion-input type="text" formControlName="wordInput"></ion-input>
        </ion-item>
      </ion-col>
    </ion-row>

    <ion-row>
      <ion-col>
        <ion-item>
          <ion-label>Idioma</ion-label>
          <ion-select placeholder="Seleccione" formControlName="languageSelect">
            <ion-select-option value="en">English</ion-select-option>
            <ion-select-option value="hi">Hindi</ion-select-option>
            <ion-select-option value="es">Spanish</ion-select-option>
            <ion-select-option value="fr">French</ion-select-option>
            <ion-select-option value="ja">Japanese</ion-select-option>
            <ion-select-option value="ru">Russian</ion-select-option>
            <ion-select-option value="de">German</ion-select-option>
            <ion-select-option value="it">Italian</ion-select-option>
            <ion-select-option value="ko">Korean</ion-select-option>
            <ion-select-option value="pt-BR">Brazilian Portuguese</ion-select-option>
            <ion-select-option value="ar">Arabic</ion-select-option>
            <ion-select-option value="tr">Turkish</ion-select-option>
          </ion-select>
        </ion-item>
      </ion-col>
    </ion-row>

    <ion-row class="ion-justify-content-center">
      <ion-col>
        <ion-button color="success" type="submit" [disabled]="!wordForm.valid">Buscar</ion-button>
      </ion-col>
    </ion-row>
  </form>
</ion-grid>

<ion-card *ngFor="let data of definitions">
  <ion-card-header>
    <ion-card-subtitle color="warning">{{data.class}}</ion-card-subtitle>
    <ion-card-title>{{word}}</ion-card-title>
  </ion-card-header>

  <ion-card-content>
    {{data.definition}}
  </ion-card-content>

  <ion-card-content>
    <ion-chip *ngFor="let item of data.synonyms">
      <ion-label color="primary">{{item}}</ion-label>
    </ion-chip>
  </ion-card-content>

</ion-card>
import { Component, OnInit, OnDestroy } from '@angular/core';
import { WordsService } from '../../services/words.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Meaning } from '../../models/meaning.model';
import { Definition } from '../../models/definition.model';

@Component({
  selector: 'app-content',
  templateUrl: './content.component.html',
  styleUrls: ['./content.component.scss'],
})
export class ContentComponent implements OnInit {

  wordForm: FormGroup;
  word: string;
  meanings: Meaning[];
  definition: Definition;
  definitions: Definition[] = [];
  language: string;

  constructor(private wordService: WordsService, public fb: FormBuilder) {
    this.wordForm = this.fb.group({
      wordInput: ['', Validators.required],
      languageSelect: ['', Validators.required]
    });
   }

  ngOnInit() { }

  getWord() {
    this.definitions = [];
    this.word = this.wordForm.get('wordInput').value;
    this.language = this.wordForm.get('languageSelect').value;
    this.wordService.getWord(this.language, this.word).subscribe(
      res => {
        this.meanings = res['0'].meanings;

        for (const data of this.meanings) {
          for(const da of data.definitions){
            this.definition = da;
            this.definition.class = data.partOfSpeech;
            this.definitions.push(this.definition);
          }
        }

        console.log("Definiciones Array", this.definitions);
      },
      err => {
        console.log(err);
      }
    );
  }

}

Home.page.html

Colocamos nuestros componentes previamente realizados de la siguiente manera;

<ion-header [translucent]="true">
<app-header></app-header>
</ion-header>

<ion-content>
  <app-content></app-content>
</ion-content>

Repositorio del proyecto

Contacto

Leave a Reply

Your email address will not be published.