Wednesday, May 9, 2018

Angular - Retrieving data using http and observables

Import HttpClientModule

Add HttpClientModule to the imports array of one of the application's Angular Modules

The items in bold are the ones that are specific to adding http.

app.module.ts

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


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

Adding Http to Service

my.service.ts


import { Injectable } from "@angular/core";
import { IProduct } from "./product";
import { HttpClient } from "@angular/common/http";
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/Observable/throw'
import 'rxjs/add/operator/catch'
import 'rxjs/add/operator/do'
import { HttpErrorResponse } from "@angular/common/http";

@Injectable()
export class ThingService {
    
    private _thingUrl = 'www.myWebApi.com/api/myThings';

    constructor (private _http: HttpClient){ }

    getMyThings(): Observable<IThing[]> {
        return this._http.get<IThing[]>(this._thingUrl)
        .do(data => console.log('data: ' + JSON.stringify(data)))
        .catch(this.handleError);
    }

    private handleError(err: HttpErrorResponse) {
            return Observable.throw(err.message);
    }
}

TIP: The url can be to a local JSON file that has the desired response. This can be useful for mocking out the web service you are calling when testing or rapidly developing.

Using Service / Subscribing

Call the subscribe method of the returned observable

In your component you could have something like this.

ngOnInit(): void {
this._productService.myThings()
.subscribe(things => {
this.things = things;
}, 
error => {
                      /// handle error here...
});
}

No comments: