Explicación: Servicios http

Sitio: Campus virtual DAW - damiansu
Curso: Desarrollo Web en Entorno Cliente
Libro: Explicación: Servicios http
Imprimido por: Invitado
Día: jueves, 22 de enero de 2026, 04:40

1. Explicación

Explicación 

2. Crear proyecto

ng new posts-get --standalone --routing --style=css --skip-tests
cd posts-get
ng serve -o

3. Configurar HttpClient

HttpClient se configura una vez, en main.ts.

src/main.ts

import { bootstrapApplication } from '@angular/platform-browser';
import { provideHttpClient } from '@angular/common/http';
import { AppComponent } from './app/app.component';

bootstrapApplication(AppComponent, {
  providers: [provideHttpClient()],
}).catch(console.error);

4. Modelo (interfaz)

Tipado fuerte → errores antes de ejecutar.

ng generate interface models/post
ng g i models/post

src/app/models/post.model.ts

export interface Post {
  userId: number;
  id: number;
  title: string;
  body: string;
}

Interfaces para datos, clases para lógica

5. Servicio (GET básico)

El servicio:

  • No tiene HTML

  • Solo devuelve datos

  • No sabe quién los usa

Crear servicio:

ng g s services/posts

src/app/services/posts.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Post } from '../models/post.model'; #Cuidado aquí

@Injectable({ providedIn: 'root' })
export class PostsService {
  private readonly url = 'https://jsonplaceholder.typicode.com/posts';

  constructor(private http: HttpClient) {}

  getAll(): Observable<Post[]> {
    return this.http.get<Post[]>(this.url);
  }
}

5.1. Componente principal (consumo del GET)

Idea clave:

  • El componente inyecta el servicio

  • No hace la petición directamente

  • Guarda el resultado en un Observable

src/app/app.component.ts

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Observable } from 'rxjs';

import { PostsService } from './services/posts.service'; #Cuidado aquí
import { Post } from './models/post.model'; #Cuidado aquí

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './app.component.html',
})
export class AppComponent {
  posts$: Observable<Post[]>;

  constructor(private postsService: PostsService) {
    this.posts$ = this.postsService.getAll();
  }
}

5.2. Plantilla (mostrar los posts)

Aquí trabajamos:

  • @for → Angular 17+

  • async pipe → sin subscribe

  • Flujo reactivo limpio

src/app/app.component.html

<h1>Listado de Posts</h1>
<p>GET básico · Angular moderno</p>

<ul>
  @for (post of posts$ | async; track post.id) {
    <li>
      <h3>{{ post.title }}</h3>
      <p>{{ post.body }}</p>
    </li>
  } @empty {
    <li>No hay posts</li>
  }
</ul>

5.3. Estilos mínimos

src/app/app.component.css

ul {
  list-style: none;
  padding: 0;
}

li {
  border: 1px solid #ddd;
  border-radius: 10px;
  padding: 12px;
  margin-bottom: 10px;
  background: #fff;
}