Angular – HttpClient + rx

Retrieving Data Using Http

Observables and Reactive Extensions
Sending an Http Request
Exception Handling
Subscribing to an Observable

HttpClient Example

Prepare json file into assets

Get json data via Service (service uses HttpClient)

itemservice.service.ts

ng g service services/itemservice
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, tap, map } from 'rxjs/operators';
import { Iitem } from '../interfaces/iitem';

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

  private url = '/assets/item.json'

  constructor(private http: HttpClient) {}

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

iitem.ts

This is model interface to identify server data

export interface Iitem {
    name: string
    index: number
}

assets/item.json

This is json data to test httpclient. this data can be accessed from http://localhost:4200/assets/item.json

[
    {"name":"Item1", "index": 1},
    {"name":"Item2", "index": 2}
]

app.module.ts

Please add HttpClientModule into root module

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';

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

app.component.ts

import { Component, OnInit } from '@angular/core';
import { Iitem } from './interfaces/iitem';

import { ItemserviceService } from './services/itemservice.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [ ItemserviceService ]
})
export class AppComponent implements OnInit {
  title = 'testapp';

  products: Iitem[] = [];

  errorMessage = '';

  constructor(private itemService: ItemserviceService) {

  }

  onNotify(message: string) {
    console.log(message);
  } 

  ngOnInit() {
    this.itemService.getItems().subscribe({
      next: products => {
        this.products = products;
        console.log(this.products);
      },
      error: err => this.errorMessage = err
  });
  }
}

Main part is ngOnInit().

Get item data using httpclient and receive events using rxjs

app.component.html

<div>
  App Component

  <app-child =5 (notify)='onNotify($event)'></app-child>
  <app-testservicecomp></app-testservicecomp>

  <div *ngFor="let product of products">
    <div>{{product.name}}</div>
  </div>
</div>

コメント