Httpclient introduced
Module is introduced into
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
// import HttpClientModule after BrowserModule.
HttpClientModule,
],
declarations: [
AppComponent,
],
bootstrap: [ AppComponent ]
})
export class AppModule {}
Copy the code
Httpclient injection
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class ConfigService {
constructor(private http: HttpClient) { }
}
Copy the code
A get request
Ts defines data types
export interface Config {
heroesUrl: string;
textfile: string;
}
Copy the code
Define the service
configUrl = 'assets/config.json';
getConfig() {
// now returns an Observable of Config
returnthis.http.get<Config>(this.configUrl); // Returns an Observable<Config> {// now returns an Observable of Configreturn this.http.get<Config>(this.configUrl);
}
Copy the code
Call the service
config: Config;
showConfig() {
this.configService.getConfig()
.subscribe((data: Config) => this.config = {
heroesUrl: data['heroesUrl'],
textfile: data['textfile']
});
// or
.subscribe((data: Config) => this.config = { ...data });
}
Copy the code
Modify the returned data type
getConfigResponse(): Observable<HttpResponse<Config>> {
return this.http.get<Config>(
this.configUrl, { observe: 'response' });
}
Copy the code
- HttpResponse< Config >
- Add request parameters, {observe: ‘response’}
showConfigResponse() {
this.configService.getConfigResponse()
// resp is of type `HttpResponse<Config>`
.subscribe(resp => {
// display its headers
const keys = resp.headers.keys();
this.headers = keys.map(key =>
`${key}: ${resp.headers.get(key)}`);
// access the body directly, which is typed as `Config`.
this.config = { ... resp.body };
});
}
Copy the code
Returns the text
getTextFile(filename: string) {
// The Observable returned by get() is of type Observable<string>
// because a text response was specified.
// There's no need to pass a
type parameter to get(). return this.http.get(filename, {responseType: '
text'}) .pipe( tap( // Log the result or error data => this.log(filename, data), error => this.logError(filename, error) ) ); }Copy the code
The json request
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import {HttpClientJsonpModule} from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
// import HttpClientModule after BrowserModule.
HttpClientModule,
HttpClientJsonpModule
],
declarations: [
AppComponent,
],
bootstrap: [ AppComponent ]
})
export class AppModule {}
Copy the code
SearchHeroes (term: string): Observable {subscribe success data term = term.trim(); searchHeroes(term: string): Observable {subscribe success data term = term.trim();let heroesURL = `${this.heroesURL}?${term}`;
return this.http.jsonp(heroesUrl, 'callback').pipe(
catchError(this.handleError('searchHeroes'/ /, [])then handle the error
);
};
Copy the code
A post request
Add data
addHero (hero: Hero): Observable<Hero> {
return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
.pipe(
catchError(this.handleError('addHero', hero))
);
}
Copy the code
Transfer the trigger
this.heroesService
.addHero(newHero)
.subscribe(hero => this.heroes.push(hero));
Copy the code
Put request
Update the data
updateHero (hero: Hero): Observable<Hero> {
return this.http.put<Hero>(this.heroesUrl, hero, httpOptions)
.pipe(
catchError(this.handleError('updateHero', hero))
);
}
Copy the code
Call to update
this.heroesService.updateHero(hero);
Copy the code
The delete request
Delete the data
deleteHero (id: number): Observable<{}> {
const url = `${this.heroesUrl}/${id}`; // DELETE api/heroes/42
return this.http.delete(url, httpOptions)
.pipe(
catchError(this.handleError('deleteHero'))); }Copy the code
The method call triggers the request
this.heroesService
.deleteHero(hero.id)
.subscribe();
Copy the code