Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Http post and get request in angular 6

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?

like image 637
unos baghaii Avatar asked May 06 '18 04:05

unos baghaii


People also ask

Can Angular handle post request?

It is a bit awkward requirement since Angular is JavaScript framework and It does not accept post request because post request needs to be handled at server side only not at client side.

What does HTTP GET return in Angular?

get() method is an asynchronous method that performs an HTTP get request in Angular applications and returns an Observable. And that Observable emits the requested data when the response is received from the server.

How do you pass multiple parameters in HTTP request in Angular 6?

Passing multiple parameters to Http get requestBy using HttpParams. append() we can pass multiple parameters to HttpClient. get() method. We have to pass page & per_page parameters to the list of users API.

What is the use of HttpClient get () method?

Use the HttpClient.get() method to fetch data from a server. The asynchronous method sends an HTTP request, and returns an Observable that emits the requested data when the response is received. The return type varies based on the observe and responseType values that you pass to the call.


2 Answers

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

like image 172
unos baghaii Avatar answered Sep 25 '22 17:09

unos baghaii


You can do a post/get using a library which allows you to use HttpClient with strongly-typed callbacks.

The data and the error are available directly via these callbacks.

The library is called angular-extended-http-client.

angular-extended-http-client library on GitHub

angular-extended-http-client library on NPM

Very easy to use.

Traditional approach

In the traditional approach you return Observable<HttpResponse<T>> from Service API. This is tied to HttpResponse.

With this approach you have to use .subscribe(x => ...) in the rest of your code.

This creates a tight coupling between the http layer and the rest of your code.

Strongly-typed callback approach

You only deal with your Models in these strongly-typed callbacks.

Hence, The rest of your code only knows about your Models.

Sample usage

The strongly-typed callbacks are

Success:

  • IObservable<T>
  • IObservableHttpResponse
  • IObservableHttpCustomResponse<T>

Failure:

  • IObservableError<TError>
  • IObservableHttpError
  • IObservableHttpCustomError<TError>

Add package to your project and in your app module

import { HttpClientExtModule } from 'angular-extended-http-client'; 

and in the @NgModule imports

  imports: [     .     .     .     HttpClientExtModule   ], 

Your Models

 export class SearchModel {     code: string; }  //Normal response returned by the API. export class RacingResponse {     result: RacingItem[]; }  //Custom exception thrown by the API. export class APIException {     className: string; } 

Your Service

In your Service, you just create params with these callback types.

Then, pass them on to the HttpClientExt's get method.

import { Injectable, Inject } from '@angular/core' import { SearchModel, RacingResponse, APIException } from '../models/models' import { HttpClientExt, IObservable, IObservableError, ResponseType, ErrorType } from 'angular-extended-http-client'; . .  @Injectable() export class RacingService {      //Inject HttpClientExt component.     constructor(private client: HttpClientExt, @Inject(APP_CONFIG) private config: AppConfig) {      }      //Declare params of type IObservable<T> and IObservableError<TError>.     //These are the success and failure callbacks.     //The success callback will return the response objects returned by the underlying HttpClient call.     //The failure callback will return the error objects returned by the underlying HttpClient call.     searchRaceInfo(model: SearchModel, success: IObservable<RacingResponse>, failure?: IObservableError<APIException>) {         let url = this.config.apiEndpoint;          this.client.post<SearchModel, RacingResponse>(url, model,                                                        ResponseType.IObservable, success,                                                        ErrorType.IObservableError, failure);     } } 

Your Component

In your Component, your Service is injected and the searchRaceInfo API called as shown below.

  search() {           this.service.searchRaceInfo(this.searchModel, response => this.result = response.result,                                                   error => this.errorMsg = error.className);    } 

Both, response and error returned in the callbacks are strongly typed. Eg. response is type RacingResponse and error is APIException.

like image 28
Shane Avatar answered Sep 21 '22 17:09

Shane