Http post and get request in angular 6

2019-02-03 04:14发布

In angular 5.2.x for http get and post I had this code:

post(url: string, model: any): Observable<boolean> {

return this.http.post(url, model)
  .map(response => response)
  .do(data => console.log(url + ': ' + JSON.stringify(data)))
  .catch(err => this.handleError(err));
 }
 get(url: string): Observable<any> {

return this.http.get(url)
  .map(response => response)
  .do(data =>
    console.log(url + ': ' + JSON.stringify(data))
  )
  .catch((error: any) => Observable.throw(this.handleError(error)));
 }

In angular 6 it doesn't work.

How can we make an HTTP post or get request?

1条回答
家丑人穷心不美
2楼-- · 2019-02-03 04:48

Update : In angular 7, they are the same as 6

In angular 6

the complete answer found in live example

  /** POST: add a new hero to the database */
  addHero (hero: Hero): Observable<Hero> {
 return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
  .pipe(
    catchError(this.handleError('addHero', hero))
  );
}
  /** GET heroes from the server */
 getHeroes (): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
  .pipe(
    catchError(this.handleError('getHeroes', []))
  );
}

it's because of pipeable/lettable operators which now angular is able to use tree-shakable and remove unused imports and optimize the app

some rxjs functions are changed

do -> tap
catch -> catchError
switch -> switchAll
finally -> finalize

more in MIGRATION

and Import paths

For JavaScript developers, the general rule is as follows:

rxjs: Creation methods, types, schedulers and utilities

import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent } from 'rxjs';

rxjs/operators: All pipeable operators:

import { map, filter, scan } from 'rxjs/operators';

rxjs/webSocket: The web socket subject implementation

import { webSocket } from 'rxjs/webSocket';

rxjs/ajax: The Rx ajax implementation

import { ajax } from 'rxjs/ajax';

rxjs/testing: The testing utilities

import { TestScheduler } from 'rxjs/testing';

and for backward compatability you can use rxjs-compat

查看更多
登录 后发表回答