0

i have a problem receiving data to variable.

this works:

    this.http.get(some_url).subscribe(
        data => {
            console.log(JSON.parse(data['_body']))
    });

but if i try to get the value to a variable instead of printing it, it does not work:

    this.http.get(some_url).subscribe(
        data => {
            this.var = JSON.parse(data['_body'])
    });

i need your help, i tried everything. Thanks!

1 Answer 1

0

This doesn't seem to be an angular 2 issue. Can you try the following steps to debug?

  1. Check the console (F12) for any errors while making the GET call
  2. Print and store the returned the data in the variable
  3. Are there any lines above the variable assignment line that you have not posted?

I've created a plunker where you can see the variable assignment in action https://embed.plnkr.co/MEHTZ92HgZhEbUZlBELQ/

the app.component.ts is as follows

import { Component } from '@angular/core';
import { Http } from '@angular/http';

@Component({
  selector: 'my-app',
  template: `
    <div>
      <p>Content: {{ content }}</p>
    </div>
  `,
})
export class AppComponent {

  content: string;

  constructor(private http: Http) {
   this.http.get('https://jsonplaceholder.typicode.com/posts/1').subscribe(
        data => {
            this.content = data
    });
  }

}

And the result I get is

Content: Response with status: 200 OK for URL: https://jsonplaceholder.typicode.com/posts/1

Of course, one shouldn't use the constructor for network calls and similar heavy stuff and should use ngOnInit instead, but just for the sake of example I've made the call in the constructor

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.