angular学习010HTTP

参考:https://www.angular.cn/tutorial/toh-pt6


1、在AppModule中配置HttpClientModule

import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {HttpClientModule} from '@angular/common/http';
@NgModule({
...
  imports: [
    HttpClientModule
  ]
...
})
export class AppModule {
}

2、在服务中使用http获取数据

import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';

import {Hero} from '../hero';
import {Observable, of} from 'rxjs';
import {MessageService} from './message.service';
import {catchError} from 'rxjs/operators';

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

@Injectable()
export class HeroService {
  constructor(
    private http: HttpClient,
    private messageService: MessageService) {
  }

  getHeroes(): Observable {
    this.log('heroes');
    const url = '/angular/hero';
    return this.http.get(url).pipe(
      catchError(this.handleError('getHeroes', []))
    );
  }

  getHero(id: string): Observable {
    this.log(id);
    const url = '/angular/hero/' + id;
    return this.http.get(url).pipe(
      catchError(this.handleError('getHero'))
    );
  }

  add(name: string): Observable {
    this.log(name);
    const url = '/angular/hero?name=' + name;
    return this.http.put(url, httpOptions).pipe(
      catchError(this.handleError('add'))
    );
  }

  update(hero: Hero): Observable {
    this.log(JSON.stringify(hero));
    const url = '/angular/hero';
    return this.http.post(url, hero, httpOptions).pipe(
      catchError(this.handleError('getHero'))
    );
  }

  delete(id: string): Observable {
    this.log('delete id:' + id);
    const url = '/angular/hero/' + id;
    return this.http.delete(url, httpOptions).pipe(
      catchError(this.handleError('delete hero'))
    );
  }

  private log(message: any) {
    this.messageService.add('message:' + message);
  }

  private handleError(option = 'option', result ?: T) {
    return (error: any): Observable => {
      console.log(error);
      console.log(option);
      return of(result as T);
    };
  }
}

3、处理数据

import {Component, OnInit} from '@angular/core';
import {Hero} from '../hero';
import {HeroService} from '../service/hero.service';

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css'],
  providers: [HeroService],
})

export class HeroesComponent implements OnInit {

  heroes: Hero[];

  constructor(private heroService: HeroService) {
  }

  ngOnInit() {
    this.getHeroes();
  }

  getHeroes(): void {
    this.heroService.getHeroes()
      .subscribe(data => {
        this.heroes = data;
      });
  }

  add(name: string): void {
    this.heroService.add(name).subscribe(
      data => {
        this.heroes.push(data);
      }
    );
  }

  delete(hero: Hero): void {
    this.heroes = this.heroes.filter(h => h !== hero);
    this.heroService.delete(hero.id).subscribe();
  }
}

4、由于跨域,需要配置文件

D:\angular\my-app\proxy.config.json
{
  "/":{
    "target":"http://127.0.0.1:8080"
  }
}

修改配置文件

D:\angular\my-app\package.json
{
  "name": "my-app",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve --proxy-config proxy.config.json",
...
  },
  ...
}

5、遗留问题,启动ng serve --proxy-config proxy.config.json时报错,不影响功能

ERROR in src/app/service/hero.service.ts(31,5): error TS2322: Type 'Observable' is not assignable to type 'Observable'.
  Type 'Object | Hero' is not assignable to type 'Hero'.
    Type 'Object' is not assignable to type 'Hero'.
      The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
        Property 'id' is missing in type 'Object'.
src/app/service/hero.service.ts(39,5): error TS2322: Type 'Observable' is not assignable to type 'Observable'.
src/app/service/hero.service.ts(47,5): error TS2322: Type 'Observable' is not assignable to type 'Observable'.

你可能感兴趣的:(angular学习,angula)