Import HttpClientModule
Add HttpClientModule to the imports array of one of the application's Angular ModulesThe 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';
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.tsimport { 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);
}
}
Using Service / Subscribing
Call the subscribe method of the returned observableIn your component you could have something like this.
ngOnInit(): void {
this._productService.myThings()
.subscribe(things => {
this.things = things;
},
error => {
/// handle error here...
});
}
No comments:
Post a Comment