发表于: 2020-01-06 23:23:13

1 1468


今日完成:

import { Injectable } from '@angular/core';
import {Herofrom './hero';
import {HttpClient,HttpHeadersfrom '@angular/common/http';
import {Observable,offrom 'rxjs';
import {MessageServicefrom './message.service';
import { CATCH_ERROR_VAR } from '@angular/compiler/src/output/output_ast';
import {catchError,map,tapfrom 'rxjs/operators';
 


const httpOptions ={
  headers: new HttpHeaders({'Content-Type':'application/json'})
};
@Injectable({
  providedIn: 'root'

})


export class HeroService {

  getHeroes(): Observable<Hero[]>{
    
    return this.http.get<Hero[]>(this.heroesUrl).pipe(
      tap(_=>this.log('fetched heroes')),
      catchError(this.handleError<Hero[]>('getHeroes',[]))
    )
  }

  getHero(id:number): Observable<Hero> {
    this.messageService.add(`HeroService: fetched hero id=${id}`);
    const url=`${this.heroesUrl}/${id}`;
    return this.http.get<Hero>(url).pipe(
      tap(_=>this.log(`fetched hero id=${id}`)),
      catchError(this.handleError<Hero>( `getHero id=${id}`))
    )
  }

  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'))
    )
  }

  addHero(heroHero):Observable<Hero> {
    return this.http.post<Hero>(this.heroesUrl,hero,httpOptions).pipe(
      tap((newHero:Hero=> this.log(`added hero w/ id=${newHero.id}`)),
      catchError(this.handleError<Hero>('addHero'))
    );
  }
  deleteHero(hero:Hero |number): Observable<Hero> {
    const id =typeof hero === 'number'hero :hero.id;
    const url = `${this.heroesUrl}/${id}`;
    return this.http.delete<Hero>(url,httpOptions).pipe(
      tap(_=>this.log(`deleted hero id = ${id}`)),
      catchError(this.handleError<Hero>('deleteHero'))
    )
  }

  private log(messagestring){
    this.messageService.add(`HeroService: ${message}`);
  }


  private handleError<T> (operation = 'operation',result?:T){
    return (errorany): Observable<T>=>{
      console.error(error);
      this.log(`${operation} failed: ${error.message}`);
      return of (result as T);
    }
  }

  private heroesUrl = 'api/heroes';

  constructor(private messageServiceMessageService,
              private http:HttpClient
    ) { }

    
}



import { TestBed } from '@angular/core/testing';

import { AuthService } from './auth.service';

describe('AuthService', () => {
  beforeEach(() => TestBed.configureTestingModule({}));

  it('should be created', () => {
    const serviceAuthService = TestBed.get(AuthService);
    expect(service).toBeTruthy();
  });
});



返回列表 返回列表
评论

    分享到