3
votes

I am posing the data on the server in angular with http post request and with rxjs but even after importing map property of rxjs this is giving an error.

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

import 'rxjs/add/operator/map';

@Injectable({
   providedIn: 'root'
})
export class AuthService {


  constructor(private http:HttpClient) { }

  registerUser(user){
    let headers = new HttpHeaders();
    headers.append('content-type','application/json');

    return this.http.post('http://localhost:8080/users/register',user,{headers:headers})
          .map(response =>response.json())
          .catch(this.errorHandler)

  }


  errorHandler(error:HttpErrorResponse){
     return throwError(error.message||"Server not responding");
  }

}

i even import map property like this:

import {map} from 'rxjs/add/operator';

Error:

Property 'map' does not exist on type 'Observable<Object>'

User is a object

3

3 Answers

1
votes

If you are using RXJS 6 or above, the usage of operators has changed a bit.

You import by:

import { map, catchError } from 'rxjs/operators';

You use the map inside of the pipe operator, like:

return this.http.post('http://localhost:8080/users/register',user,{headers:headers})
      .pipe(
          map(response => {
              // doSomething 
          }),
          catchError(error => {
              this.errorHandler(error);
              return of(`Caught an error: ${error}`);
          })
      );
0
votes
  • From RxJS v6 and up, support for calling operators directly on Observables are deprecated. Instead, use Observable.pipe.
  • From RxJS v6 and up, support for directly importing operators has been deprecated. Instead, import from rxjs/operators.
  • HttpClient (from @angular/common/http) by default maps responses as JSON. No need for the map operator (this is the former behaviour for Http (from @angular/http)).

See below for a corrected example:

import { /* imports go here */ } from '@angular/common/http';
// ...

// ...
export class AuthService {
  // ...

  registerUser(user){
    let headers = new HttpHeaders();
    headers.append('content-type','application/json');

    return this.http.post('http://localhost:8080/users/register',user,{headers:headers})
          .catch(this.errorHandler);

  }
}
0
votes

If you are using RXJS 6 or above, you have to pipe the operation

 this.http.post('http://localhost:8080/users/register',user,{headers:headers})
 .pipe(map(response => {
   // do something with response and return it
 })
 catchError(this.errorHandler)
  );

also if you are using HttpClient instead of Http then there is no need for response.json() as response will be deserialized json.