0

I'm using the latest angular, imports and other angular things are normal. I have such code:

...class definition
ngOnInit(){
 this.http.get("http://localhost:5000/getData").subscribe(data => {
  this.data = data;
});
}

Where localhost:5000/getData returns data in json. And angular is on the http://localhost:4200/ and it has its own routers. The data is correct, but I'm unable to use this.data outside the subscribe() method(no errors just this.data field is empty). Where am I wrong? What should I do to fix it?(I fixed troubles with same origin policy because other things work in normal way). I have to display data from the server into my component;

4
  • when you trying to use what error you are getting? and where you are using? Commented Nov 10, 2017 at 20:59
  • I don't have any errors my this.data is empty and that's all Commented Nov 10, 2017 at 21:00
  • is it empty all the time? where are you using the this.data Commented Nov 10, 2017 at 21:07
  • I initialized it in the class definition, in subscribe method this.data has value, but outside subscribe this.data has no value again. I use it in my component Commented Nov 10, 2017 at 21:21

2 Answers 2

1

subscribe is asynchronous, you can't get the value while initialization of the component that way, the value is not available yet, if you have some action to do with data, you can call a function inside subscribe:

this.http.get("http://localhost:5000/getData").subscribe(data => {
   this.data = data;
   this.doAction(this.data);
});

you can use async Pipe to display data in the view: change your code and use .map thus an Observable will be returned :

import 'rxjs/add/operator/map';
this.data= this.http.get("http://localhost:5000/getData")
              .map(response => response.json());

and in your view use async pipe, no need to subscribe

<div *ngFor="let item of (data | asyn)"> {{item}}</div>
Sign up to request clarification or add additional context in comments.

5 Comments

I only have to display my data into component
Do I have to take map() from rxjs?
you don't need to import anything
by the default I don't have property map()
import 'rxjs/add/operator/map';
0
    private display = "downloading";    
    ngOnInit(){
     new Promise((resolve,reject)=>{ 
      this.http.get("http://localhost:5000/getData").subscribe(data => {
       resolve(data);                  
      });    
     }).then(data=>{
      if(data['someKey']!==undefined){  
       this.display = "downloaded";    
       this.data = data;            
      }else{this.display = "noData";}   
     });
   }

It's my solution where I show different views while data are loading from the server. View depends on display

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.