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);
  }
}