Make a map of a REST Web API response

2

I'm trying to do a map of a response from a Web REST API . At the moment of doing .map on the object http.get the TypeScript returns this error:

  

The 'map' property does not exist in the 'Observable'.ts (2339) "type

I clarify that I imported the map in the following way, import 'rxjs/add/operator/map; . I also tried with import { map } from 'rxjs/operators'; and I keep checking the same error. How can I solve this problem?

The versions I have are:

  • Angular CLI : 7.0.7
  • Node : 11.1.0
  • Angular : 7.0.4
  • rxjs : 6.3.3
  • typescript : 3.1.6

I enclose the code with the error. Only the .map is marked with error.

getinfo(){
    this.http.get(this.url).map((resp:any) => {
      this.info = resp;
      return this.info;
    };   
}
    
asked by Esteban 25.12.2018 в 19:12
source

2 answers

1

I leave the solution I found

we make the following import into the service:

import {map} from 'rxjs / operators';

and the code would be

getinfo(){

this.http.get(this.url).pipe(map((resp:any) =>{
  this.info = resp;

}))}

You have to enter a .pipe and then the map complete the entire map sentence so that the error is completely eliminated.

    
answered by 25.12.2018 в 19:31
1

The operator map is a transformer, what it does is that it takes the value that touches it in the chain of operators in pipe and returns a new value based on that, which could be the input value of another operator or be the final value.

Suppose you get a number 2 in your API :

this.http.get(this.url).pipe(
    map(n => { return n * 2}), // 2*2=4
    map(n => { return n * 4})  // 4*4=16
)

The value at the end would be 16, because the original value was transformed through the map . For that reason, you would be using it badly, because what you are interested in is creating a secondary effect from the value that comes in the HTTP response, not transforming that same response .

You could use the tap operator instead, whose goal is exactly what you want to do: Use the response value without transforming it.

this.http.get(this.url).pipe(
    tap(n => { console.log(n * 2)}), // 2*2=4
    tap(n => { console.log(n * 4)})  // 2*4=8
)

Of course map is working for you, as could filter or so many other operators that exist in rxjs , but it's better to use tap since it was created for that.

Now, on the other hand, you could accomplish the same thing in other ways that would make more sense. For example:

  • Subscribing to Observable returned by this.http.get() would give you the same results ... But you would have to manage the life cycle of the subscription.
  • You could also use this.http.get(this.url).toPromise() and handle yourself as if it were a Promise ... But it would be swimming in redundancy.
  • Use async pipe . I strongly recommend this option , because it's simple, you do not have to handle the Observable life cycle and your code will look better. How to use async pipe
answered by 26.12.2018 в 07:10