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 {}複製代碼
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class ConfigService {
constructor(private http: HttpClient) { }
}複製代碼
export interface Config {
heroesUrl: string;
textfile: string;
}複製代碼
configUrl = 'assets/config.json';
getConfig() {
// now returns an Observable of Config
return this.http.get<Config>(this.configUrl);
}
//等效於
getConfig():Observable<Config> {
// now returns an Observable of Config
return this.http.get<Config>(this.configUrl);
}複製代碼
config: Config;
showConfig() {
this.configService.getConfig()
.subscribe((data: Config) => this.config = {
heroesUrl: data['heroesUrl'],
textfile: data['textfile']
});
// or
.subscribe((data: Config) => this.config = { ...data });
}複製代碼
getConfigResponse(): Observable<HttpResponse<Config>> {
return this.http.get<Config>(
this.configUrl, { 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 };
});
}複製代碼
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 <string> 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)
)
);
}複製代碼
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 {}複製代碼
searchHeroes(term: string): Observable { // 利用subscribe訂閱成功數據
term = term.trim();
let heroesURL = `${this.heroesURL}?${term}`;
return this.http.jsonp(heroesUrl, 'callback').pipe(
catchError(this.handleError('searchHeroes', []) // then handle the error
);
};複製代碼
addHero (hero: Hero): Observable<Hero> {
return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
.pipe(
catchError(this.handleError('addHero', hero))
);
}複製代碼
this.heroesService
.addHero(newHero)
.subscribe(hero => this.heroes.push(hero));複製代碼
updateHero (hero: Hero): Observable<Hero> {
return this.http.put<Hero>(this.heroesUrl, hero, httpOptions)
.pipe(
catchError(this.handleError('updateHero', hero))
);
}複製代碼
this.heroesService.updateHero(hero);複製代碼
deleteHero (id: number): Observable<{}> {
const url = `${this.heroesUrl}/${id}`; // DELETE api/heroes/42
return this.http.delete(url, httpOptions)
.pipe(
catchError(this.handleError('deleteHero'))
);
}複製代碼
this.heroesService
.deleteHero(hero.id)
.subscribe();複製代碼
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token'
})
};複製代碼
httpOptions.headers =
httpOptions.headers.set('Authorization', 'my-new-auth-token');複製代碼
getConfig() {
return this.http.get<Config>(this.configUrl)
.pipe(
catchError(this.handleError)
);
}複製代碼
getConfig() {
return this.http.get<Config>(this.configUrl)
.pipe(
retry(3), // retry a failed request up to 3 times
catchError(this.handleError) // then handle the error
);
}複製代碼
showConfig() {
this.configService.getConfig()
.subscribe(
(data: Config) => this.config = { ...data }, // success path
error => this.error = error // error path
);
}複製代碼
本文做者:前端首席體驗師(CheongHu)聯繫郵箱:simple2012hcz@126.com版權聲明: 本文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明出處!前端