Dheeraj Kumar
Dheeraj Kumar

Reputation: 4175

Response of Http Api call promise is undefined - Angular 2

I have created an api in WebAPI as below.

public HttpResponseMessage Get() {

            var response = Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new StringContent(JsonConvert.SerializeObject("Hello World"), Encoding.UTF8, "application/json");
            return response;
        }

I am trying to call it from Angular as below

Service.ts

@Injectable()
export class DemoService {

     constructor(private http:Http){}

     GetHttpData(){

        return this.http.get('http://localhost:54037/api/home')
        .map((res:Response)=>res.json());
     }

Component:

export class AppComponent implements OnInit  { 

  data2: String;
  constructor(private s: DemoService){} 

  ngOnInit(){

    this.s.GetHttpData().subscribe(data=>this.data2=data);
    console.log("Http call  completed: "+this.data2);

}

On running the application, I get output:

Http call completed: undefined

Can someone help with this?

Thanks

Upvotes: 1

Views: 738

Answers (2)

k11k2
k11k2

Reputation: 2044

Put the console.log inside the data function.

Could you try like this.

export class AppComponent implements OnInit  { 

  data2: String;
  constructor(private s: DemoService){} 

  ngOnInit(){

    this.s.GetHttpData().subscribe(data=>{
        this.data2=data;
        console.log("Http call  completed: "+this.data2)
    });

}

Upvotes: 1

Marian König
Marian König

Reputation: 784

Try to work with a simple promise here.

In Service.ts (DemoService)

 GetHttpData() {

        return new Promise(resolve => {

            this.http.get('http://localhost:54037/api/home')
                .map(res => res.json())
                .subscribe(data => {
            resolve(data);
        });
    }

And in Component:

this.s.GetHttpData()
        .then(data => { 
             console.log("Http call  completed: "+data);
});

Upvotes: 1

Related Questions