Reputation: 521
How can I get a variable outside of a promise block in a component in Angular 6?
For example
items:string[]=[];
ngOnInit{
const url='SOME URL';
const promise = this.apiService.post(url);
//Response
promise.then(response => {
this.items.push('abc');
this.items.push('def');
});
this.items.forEach(item=>{
alert(item);
});
}
I expect that the application alerts the contents of the items array
Upvotes: 0
Views: 310
Reputation: 136
It seems to be an async issue, I mean your alert is being shown before you get data from the service, so an option would be to work with Observables
and subscribe
. It should wait until getting data before using it.
Also you could try using async/await
following this medium article
Upvotes: 0
Reputation: 563
When you do
this.items.forEach(item=>{
alert(item);
});
the items array is empty.
You need put this code inside
promise.then(response => {
this.items.push('abc');
this.items.push('def');
this.items.forEach(item=>{
alert(item);
});
});
Or you can use Observables to know when the promise ends and execute the foreach, you need to do something like this:
private subjectItems = new Subject<any>();
ngOnInit{
this.subjectItems.asObservable().subscribe(o => {
this.items.forEach(item=>{
alert(item);
});
});
const url='SOME URL';
const promise = this.apiService.post(url);
//Response
promise.then(response => {
this.items.push('abc');
this.items.push('def');
this.subjectItems.next(this.items)
});
}
Upvotes: 2