1

I hope somebody can help. I´ve created a new asp.net core angular project in visual studio and a simple api method just like this:

[Produces("application/json")]
[Route("api/Users")]
public class UsersController : Controller
{
    [HttpGet("[action]")]
    public async Task<JsonResult> CheckAPIConnection()
    {
        return Json(new { success = true }); 
    }

then I´ve created a new service in angular

    import { Injectable } from '@angular/core'; 
import { Http } from '@angular/http'; 
import { Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map'; 

@Injectable() 
export class ApiService {
    constructor(private http: Http) {

}

checkAPIConnection() {
    let result = this.http.get("/api/Users/CheckAPIConnection");
    let jso:any;
    result.subscribe(res => jso = res);
    console.log(jso);
    if (jso.success == true) return true;
    else return false; 
}

In fiddler the request succeeds and the response is correct. But console.log tells me that "jso" is undefined. So I´ve tried to add

result.subscribe(res => jso = res.json());

but this does not change anything. I´ve also tried to enter "jso" with jso["success"] but I think the mayor problem is that jso is undefined.

I´ve tried to search for solutions but everbody used something like then() instead of subscribe(). Am i missing some imports or so? (Sorry I´m very new to angular especially in receiving data from api)

0

2 Answers 2

4

Try to console.log inside the subscription as

result.subscribe(res => {
       jso = res.json();
       console.log(jso);
});

Alternatively, you can use do operator of rxjs to check if the data is returned from service or not as below,

result.subscribe(res => jso = res)
      .do(response =>  console.log(response));

Reason :

  • Http Request is async so log statement will be executed before the result is binded to variable.
Sign up to request clarification or add additional context in comments.

Comments

0

you should use result.subscribe(res => this.jso = res);

1 Comment

jso is a local variable, so this.jso is not valid.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.