docs: migrate examples from @angular/http to @angular/common/http (#28296)
PR Close #28296
This commit is contained in:
committed by
Kara Erickson
parent
4b9eb6185f
commit
a29ce57732
@@ -1,126 +0,0 @@
|
||||
/**
|
||||
* Test the HeroService when implemented with the OLD HttpModule
|
||||
*/
|
||||
import {
|
||||
async, inject, TestBed
|
||||
} from '@angular/core/testing';
|
||||
|
||||
import {
|
||||
MockBackend,
|
||||
MockConnection
|
||||
} from '@angular/http/testing';
|
||||
|
||||
import {
|
||||
HttpModule, Http, XHRBackend, Response, ResponseOptions
|
||||
} from '@angular/http';
|
||||
|
||||
import { of } from 'rxjs';
|
||||
|
||||
import { Hero } from './hero';
|
||||
import { HttpHeroService } from './http-hero.service';
|
||||
|
||||
const makeHeroData = () => [
|
||||
{ id: 1, name: 'Windstorm' },
|
||||
{ id: 2, name: 'Bombasto' },
|
||||
{ id: 3, name: 'Magneta' },
|
||||
{ id: 4, name: 'Tornado' }
|
||||
] as Hero[];
|
||||
|
||||
//////// Tests /////////////
|
||||
describe('HttpHeroService (using old HttpModule)', () => {
|
||||
let backend: MockBackend;
|
||||
let service: HttpHeroService;
|
||||
|
||||
beforeEach( () => {
|
||||
TestBed.configureTestingModule({
|
||||
imports: [ HttpModule ],
|
||||
providers: [
|
||||
HttpHeroService,
|
||||
{ provide: XHRBackend, useClass: MockBackend }
|
||||
]
|
||||
});
|
||||
});
|
||||
|
||||
it('can instantiate service via DI', () => {
|
||||
service = TestBed.get(HttpHeroService);
|
||||
expect(service instanceof HttpHeroService).toBe(true);
|
||||
});
|
||||
|
||||
it('can instantiate service with "new"', () => {
|
||||
const http = TestBed.get(Http);
|
||||
expect(http).not.toBeNull('http should be provided');
|
||||
let service = new HttpHeroService(http);
|
||||
expect(service instanceof HttpHeroService).toBe(true, 'new service should be ok');
|
||||
});
|
||||
|
||||
it('can provide the mockBackend as XHRBackend', () => {
|
||||
const backend = TestBed.get(XHRBackend);
|
||||
expect(backend).not.toBeNull('backend should be provided');
|
||||
});
|
||||
|
||||
describe('when getHeroes', () => {
|
||||
let fakeHeroes: Hero[];
|
||||
let http: Http;
|
||||
let response: Response;
|
||||
|
||||
beforeEach(() => {
|
||||
|
||||
backend = TestBed.get(XHRBackend);
|
||||
http = TestBed.get(Http);
|
||||
|
||||
service = new HttpHeroService(http);
|
||||
fakeHeroes = makeHeroData();
|
||||
let options = new ResponseOptions({status: 200, body: {data: fakeHeroes}});
|
||||
response = new Response(options);
|
||||
});
|
||||
|
||||
it('should have expected fake heroes (then)', () => {
|
||||
backend.connections.subscribe((c: MockConnection) => c.mockRespond(response));
|
||||
|
||||
service.getHeroes().toPromise()
|
||||
// .then(() => Promise.reject('deliberate'))
|
||||
.then(heroes => {
|
||||
expect(heroes.length).toBe(fakeHeroes.length,
|
||||
'should have expected no. of heroes');
|
||||
})
|
||||
.catch(fail);
|
||||
});
|
||||
|
||||
it('should have expected fake heroes (Observable tap)', () => {
|
||||
backend.connections.subscribe((c: MockConnection) => c.mockRespond(response));
|
||||
|
||||
service.getHeroes().subscribe(
|
||||
heroes => {
|
||||
expect(heroes.length).toBe(fakeHeroes.length,
|
||||
'should have expected no. of heroes');
|
||||
},
|
||||
fail
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
it('should be OK returning no heroes', () => {
|
||||
let resp = new Response(new ResponseOptions({status: 200, body: {data: []}}));
|
||||
backend.connections.subscribe((c: MockConnection) => c.mockRespond(resp));
|
||||
|
||||
service.getHeroes().subscribe(
|
||||
heroes => {
|
||||
expect(heroes.length).toBe(0, 'should have no heroes');
|
||||
},
|
||||
fail
|
||||
);
|
||||
});
|
||||
|
||||
it('should treat 404 as an Observable error', () => {
|
||||
let resp = new Response(new ResponseOptions({status: 404}));
|
||||
backend.connections.subscribe((c: MockConnection) => c.mockRespond(resp));
|
||||
|
||||
service.getHeroes().subscribe(
|
||||
heroes => fail('should not respond with heroes'),
|
||||
err => {
|
||||
expect(err).toMatch(/Bad response status/, 'should catch bad response status code');
|
||||
return of(null); // failure is the expected test result
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,69 +0,0 @@
|
||||
// The OLD Http module. See HeroService for use of the current HttpClient
|
||||
// #docplaster
|
||||
// #docregion
|
||||
import { Injectable } from '@angular/core';
|
||||
import { Http, Response } from '@angular/http';
|
||||
import { Headers, RequestOptions } from '@angular/http';
|
||||
import { Hero } from './hero';
|
||||
|
||||
import { Observable } from 'rxjs';
|
||||
import { throwError } from 'rxjs';
|
||||
import { catchError, map } from 'rxjs/operators';
|
||||
|
||||
@Injectable()
|
||||
export class HttpHeroService {
|
||||
private _heroesUrl = 'app/heroes'; // URL to web api
|
||||
|
||||
constructor (private http: Http) {}
|
||||
|
||||
getHeroes (): Observable<Hero[]> {
|
||||
return this.http.get(this._heroesUrl).pipe(
|
||||
map(this.extractData),
|
||||
// tap(data => console.log(data)), // eyeball results in the console
|
||||
catchError(this.handleError)
|
||||
);
|
||||
}
|
||||
|
||||
getHero(id: number | string) {
|
||||
return this.http.get('app/heroes/?id=${id}').pipe(
|
||||
map((r: Response) => r.json().data as Hero[])
|
||||
);
|
||||
}
|
||||
|
||||
addHero (name: string): Observable<Hero> {
|
||||
let body = JSON.stringify({ name });
|
||||
let headers = new Headers({ 'Content-Type': 'application/json' });
|
||||
let options = new RequestOptions({ headers: headers });
|
||||
|
||||
return this.http.post(this._heroesUrl, body, options).pipe(
|
||||
map(this.extractData),
|
||||
catchError(this.handleError)
|
||||
);
|
||||
}
|
||||
|
||||
updateHero (hero: Hero): Observable<Hero> {
|
||||
let body = JSON.stringify(hero);
|
||||
let headers = new Headers({ 'Content-Type': 'application/json' });
|
||||
let options = new RequestOptions({ headers: headers });
|
||||
|
||||
return this.http.put(this._heroesUrl, body, options).pipe(
|
||||
map(this.extractData),
|
||||
catchError(this.handleError)
|
||||
);
|
||||
}
|
||||
|
||||
private extractData(res: Response) {
|
||||
if (res.status < 200 || res.status >= 300) {
|
||||
throw new Error('Bad response status: ' + res.status);
|
||||
}
|
||||
let body = res.json();
|
||||
return body.data || { };
|
||||
}
|
||||
|
||||
private handleError (error: any) {
|
||||
// In a real world app, we might send the error to remote logging infrastructure
|
||||
let errMsg = error.message || 'Server error';
|
||||
console.error(errMsg); // log to console instead
|
||||
return throwError(errMsg);
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,6 @@
|
||||
'app/hero/hero-detail.component.spec',
|
||||
'app/hero/hero-list.component.spec',
|
||||
'app/model/hero.service.spec',
|
||||
'app/model/http-hero.service.spec',
|
||||
'app/shared/highlight.directive.spec',
|
||||
'app/shared/title-case.pipe.spec',
|
||||
'app/twain/twain.component.spec',
|
||||
|
||||
@@ -17,7 +17,6 @@ import './app/hero/hero-detail.component.no-testbed.spec.ts';
|
||||
import './app/hero/hero-detail.component.spec.ts';
|
||||
import './app/hero/hero-list.component.spec.ts';
|
||||
import './app/model/hero.service.spec.ts';
|
||||
import './app/model/http-hero.service.spec.ts';
|
||||
import './app/model/testing/http-client.spec.ts';
|
||||
import './app/shared/highlight.directive.spec.ts';
|
||||
import './app/shared/title-case.pipe.spec.ts';
|
||||
|
||||
Reference in New Issue
Block a user