JustDoItTomorrow
3/15/2018 - 8:03 AM

发送数据

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';

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

@Injectable()
export class HeroService {

  private heroesUrl = 'api/heroes';

  constructor(private http: HttpClient) { }

  getHeroes() {
    return this.http.get(this.heroesUrl);
  }

  getHero(id: number) {
    return this.http.get(`${this.heroesUrl}/${id}`);
  }

  updateHero(hero) {
    return this.http.put(this.heroesUrl, hero, httpOptions);
  }

  addHero(hero) {
    return this.http.post(this.heroesUrl, hero, httpOptions);
  }

  deleteHero(hero) {
    const id = typeof hero === 'number' ? hero : hero.id;
    return this.http.delete(`${this.heroesUrl}/${id}`, httpOptions);
  }

  searchHeroes(term: string) {
    if (!term.trim()) {
      return of([]);
    }
    return this.http.get(`api/heroes/?name=${term}`);
  }
}