Posted in

Ejemplos Angular (II) – Servicios, hacer uso de Json

Usaremos los servicios para compartir datos en toda nuestra aplicación.
1 – Crearemos un archivo en app y lo llamaremos posts.service.ts desde el cual haremos peticiones que nos serán devueltas mediante Json. Usaremos https://jsonplaceholder.typicode.com/ para obtener un archivo Json y poder trastear con él (Fake API). En el archivo que hemos creado añadiremos las siguientes lineas de código.

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class PostService {
    constructor(private http:Http) {
        
    }
    getPosts(){
        return this.http.get('https://jsonplaceholder.typicode.com/posts').map(res=>res.json());
    }
}

2 – Para importar en la aplicación el servicio que acabamos de crear, abriremos el archivo app.components.ts y añadiremos la linea de código para importarlo.

import { PostService } from './posts.service';

En el mismo archivo lo inyectaremos desde su decorador a través de un proveedor (providers):

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [PostService]
})

En nuestro constructor añadiremos lo siguiente:

constructor(private postService:PostService){
    this.title = '4funkies';
    this.name = "Oscar";
    this.email = "oscar@4funkies.com";
    this.website = "http://oscarperiche.com";
    this.hobbies = ['Música', 'Natura', 'Aventura'];
    this.showHobbies = false;
    this.postService.getPosts().subscribe(posts=> {
      console.log(posts);
    })
  }

3 – En el archivo app.components.ts importaremos HttpModule y lo registraremos:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule} from '@angular/http';
import { FormsModule }   from '@angular/forms'; 
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Con este ejemplo podemos comprobar en la consola que cargamos el archivo Json y se muestran los diferentes objetos.

Para hacer uso de estos datos haremos lo siguiente, abrimos el archivo app.component.ts y añadimos el tipo para “posts” y creamos la interface ya que es un tipo de array de objetos y realizamos un cambio en el constructor para que nos devuelva el array de objetos en lugar de pasarlo a la consola.

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

import { PostService } from './posts.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [PostService]
})
export class AppComponent {
  title: string;
  name: string;
  email: string;
  website: string;
  hobbies: string[];
  showHobbies: boolean;
  posts: Ipost[];

  constructor(private postService:PostService){
    this.title = '4funkies';
    this.name = "Oscar";
    this.email = "oscar@4funkies.com";
    this.website = "http://oscarperiche.com";
    this.hobbies = ['Música', 'Natura', 'Aventura'];
    this.showHobbies = false;
    this.postService.getPosts().subscribe(posts=> {
      this.posts = posts;
    })
  }

  toggleHobbies(){
    this.showHobbies = !this.showHobbies;
  }

  newHobby(hobby){
    //console.log(hobby.value);
    this.hobbies.push(hobby.value);
    hobby.value = '';
    return false;
  }

}

interface Ipost {
  id: string;
  title: string;
  body: string;
}

Deixa un comentari

L'adreça electrònica no es publicarà. Els camps necessaris estan marcats amb *


The reCAPTCHA verification period has expired. Please reload the page.