Reputation: 1523
I am following an example and they're making the call to a local web api like so.
return this.http.get("http://localhost:26264/api/news").map((response: Response)=>{
response.json();
});
If you watch the value of response before the .json()
call everything looks fine.
I am then doing this,
var data = this.authService.Login(value.Email, value.Password).subscribe((res: any)=>{
console.log(res);
});
At this point the value of res is undefined? Ignore the fact that I am calling a login method for a news controller api. I changed my api endpoint because I was getting other errors prior to this.
Upvotes: 4
Views: 5010
Reputation: 1113
You simply use the syntax incorrectly.
return this.http.get("http://localhost:26264/api/news").map((response: Response)=>{
response.json();
});
Have a look at your anonymous function (the function inside map). The function receives an input of type Response, and runs the code inside the curly brackets afterwards. For simplicity, your code is equivalent to:
myJsonifyFunc(response: Response) {
response.json();
// notice there is no return statement!
}
return this.http.get("http://localhost:26264/api/news").map(myJsonifyFunc);
There are two allowed ways to write anonymous functions as function arguments:
.....map((x,y,z) => {...})
receives x,y,z arguments and runs the code inside {...}. To return a value, you should explicitly write "return" inside the curly brackets, otherwise the function would return void (which answers your question about why does it return undefined).
.....map((x,y,z) => ...)
Notice that this time we omitted the curly brackets. The code replacing ... MUST be a single-statement, and is being returned from the function.
.....map((x,y,z) => ...)
.....map((x,y,z) => {return ...})
The two lines are equivalent, given that ... is a single statement.
Wish the point is clear.
Upvotes: 1
Reputation: 2684
Consider changing:
.map((response: Response)=>{
response.json();
});
to
.map((response: Response) => response.json())
The reason for this is..
.map(response: Response => response.json() )
says create an anonymous function and take in a response object and return the json method from the response object (which returns the object serialized as JSON)
.map((response: Response)=>{
response.json();
});
says create an anonymous function which takes in a response object, and in the scope of this anonymous function, run the json method from the response object, which returns nothing.
To fix:
.map((response: Response)=>{
return response.json();
});
Upvotes: 5