refactor: utilize type narrowing (#33075)

PR Close #33075
This commit is contained in:
Danny Skoog
2019-10-09 17:17:52 +02:00
committed by Miško Hevery
parent 1ae77da609
commit 6ab5f3648a
29 changed files with 73 additions and 80 deletions

View File

@ -15,7 +15,7 @@ export class HeroDetailService {
// Returns a clone which caller may modify safely
getHero(id: number | string): Observable<Hero> {
if (typeof id === 'string') {
id = parseInt(id as string, 10);
id = parseInt(id, 10);
}
return this.heroService.getHero(id).pipe(
map(hero => {

View File

@ -18,7 +18,7 @@ export class HeroService {
constructor(private http: HttpClient) { }
/** GET heroes from the server */
getHeroes (): Observable<Hero[]> {
getHeroes(): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
tap(heroes => this.log(`fetched heroes`)),
@ -29,7 +29,7 @@ export class HeroService {
/** GET hero by id. Return `undefined` when id not found */
getHero<Data>(id: number | string): Observable<Hero> {
if (typeof id === 'string') {
id = parseInt(id as string, 10);
id = parseInt(id, 10);
}
const url = `${this.heroesUrl}/?id=${id}`;
return this.http.get<Hero[]>(url)
@ -46,14 +46,14 @@ export class HeroService {
//////// Save methods //////////
/** POST: add a new hero to the server */
addHero (hero: Hero): Observable<Hero> {
addHero(hero: Hero): Observable<Hero> {
return this.http.post<Hero>(this.heroesUrl, hero, httpOptions).pipe(
tap((hero: Hero) => this.log(`added hero w/ id=${hero.id}`)),
tap((addedHero) => this.log(`added hero w/ id=${addedHero.id}`)),
catchError(this.handleError<Hero>('addHero'))
);
}
/** DELETE: delete the hero from the server */
deleteHero (hero: Hero | number): Observable<Hero> {
deleteHero(hero: Hero | number): Observable<Hero> {
const id = typeof hero === 'number' ? hero : hero.id;
const url = `${this.heroesUrl}/${id}`;
@ -64,7 +64,7 @@ export class HeroService {
}
/** PUT: update the hero on the server */
updateHero (hero: Hero): Observable<any> {
updateHero(hero: Hero): Observable<any> {
return this.http.put(this.heroesUrl, hero, httpOptions).pipe(
tap(_ => this.log(`updated hero id=${hero.id}`)),
catchError(this.handleError<any>('updateHero'))
@ -75,7 +75,7 @@ export class HeroService {
* This error handler lets the app continue to run as if no error occurred.
* @param operation - name of the operation that failed
*/
private handleError<T> (operation = 'operation') {
private handleError<T>(operation = 'operation') {
return (error: HttpErrorResponse): Observable<T> => {
// TODO: send the error to remote logging infrastructure

View File

@ -42,9 +42,9 @@ export class TestHeroService extends HeroService {
getHero(id: number | string): Observable<Hero> {
if (typeof id === 'string') {
id = parseInt(id as string, 10);
id = parseInt(id, 10);
}
let hero = this.heroes.find(h => h.id === id);
const hero = this.heroes.find(h => h.id === id);
return this.lastResult = asyncData(hero);
}