Reputation: 47
I am having trouble getting a part of an application that I am developing to work properly:
This is the logic of the component:
export class StockStatusComponent implements OnInit{
articles: Article[] = [];
selectedLevel: any;
constructor(private service: ArticleService) {
}
ngOnInit(): void {
this.dataBackend();
}
dataBackend() {
this.service.getArticles().subscribe(res => {
for (let i = 0; i < res.length; i++) {
let actualStock = res[i].stockActual;
let minimumStock = res[i].stockMinimo;
if (actualStock < minimumStock) {
this.articles.push(res[i]);
}
}
})
console.log(this.articles);
}
filterByLevels(event: any) {
const level = event.target.value;
this.selectedLevel = level;
}
selectLevel() {
console.log("Selected level: " + this.selectedLevel);
if (this.selectedLevel === "all") {
this.service.getArticles().subscribe(res => {
this.articles = res;
})
}
console.log(this.articles);
}
}
HTML:
<div>
<div>
<label>Filter by Stock Levels</label>
<select (change)="filterByLevels($event)">
<option value=""></option>
<option value="all">All</option>
</select>
<button class="btn btn-success" (click)="selectLevel()">Select</button>
</div>
</div>
Step to explain the code:
As soon as the component is accessed, it should show me through the console those "articles" that meet the developed condition, in this part I think I'm not having problems because it correctly brings me the desired data. (ngOnInit)
The problem I am having is when I select any of the options in the list, for example the level "all", this would have to bring me all the articles and for it to bring them I must click twice. To clarify I leave this example:
Example:
I enter the component and thanks to the method that is executed in the ngOnInit () it shows me an empty array because at the moment there are no records that match the condition.
I select the option 'all' from the list and try to bring all the records, but it brings me the same result that I obtained thanks to the ngOnInit. To achieve the desired I must click again and execute the method 'select Level ()' again.
Thank you very much in advance and I appreciate any kind of help!
Upvotes: 0
Views: 39
Reputation: 1863
selectLevel() {
console.log("Selected level: " + this.selectedLevel);
if (this.selectedLevel === "all") {
this.service.getArticles().subscribe(res => {
this.articles = res;
console.log(this.articles);
})
}
}
Put your console log inside your subscribe. This will show you your articles.
The logic of your subscribe is being executed after your first click and the console.log(this.articles) is triggered, which means the first console log is empty, on the second occurence it shows. But your data is always returned from the subscribe in the first place, just a little bit later.
You need to understand the concepts of Observables
and Promises
and how to work with them in Angular.
Upvotes: 2