Reputation: 69
I'm using this code:
private ARRAYDATA: any[];
constructor(private http: Http) {
this.getCards('data.json');
}
getCards(url)
{
this.http.get(url)
.map(response => response.json())
.subscribe(
function(response) {
console.log(response); //show object
},
function(error) { console.log("Error happened" + error)},
function() { console.log("the subscription is completed")}
);
}
This code works, now I can not understand how to pass an object RESPONSE to a variable ARRAYDATA
; Help me please!
This code does not work:
getCards(url)
{
this.http.get(url)
.map(response => response.json())
.subscribe(
function(response) {
console.log(response); //show object
this.arraydata = response;
},
function(error) { console.log("Error happened" + error)},
function() { console.log("the subscription is completed")}
);
console.log(this.arraydata)// show undefind
}
I need to use a variable ARRAYDATA outside the function. right here
constructor(private http: Http) {
this.getCards('data.json');
console.log(this.ARRAYDATA);
}
Upvotes: 1
Views: 2211
Reputation: 29614
You have two issues here.
Http responses return observables which are asynchronous and that means you can get data within the subscribe function.
You are using a regular function which means your this
will change and point to the function object rather than the class. You should use Arrow Functions for callbacks. ()=>{}
does not assign a function object to this
.
this.http.get(url)
.map(response => response.json())
.subscribe(
(response) => {
console.log(response); //show object
this.arraydata = response;
console.log(this.arraydata);
},
(error) => { console.log("Error happened" + error)},
() => { console.log("the subscription is completed")}
);
Upvotes: 3
Reputation: 376
This is totally normal. Your http get make an asynchronous call,It won't wait to the response of the http.get and go directly after the subscribe and execute the console.log()
.
Then the response will come from the server and you will affect the response to the arraydata
.
I strongly advise you to look how asynchronous work in javascript.
Hope it helps.
Upvotes: 0
Reputation: 95652
The request happens asynchronously. If you need to manipulate the result then move the code to use that data inside the callback.
getCards(url)
{
this.http.get(url)
.map(response => response.json())
.subscribe(
function(response) {
console.log(response); //show object
this.arraydata = response;
console.log(this.arraydata)// use it here!
},
function(error) { console.log("Error happened" + error)},
function() { console.log("the subscription is completed")}
);
}
A lot of angular happens asynchronously. That means you need to be prepared to wait for results to come back by using observables or promises. In this case you might be better saving the observable in a variable and then you can subscribe to the observable anywhere you need to use the value.
Upvotes: 1