What is preventing me from retrieving the data accurately? (Angular)

I'm currently facing an issue with a specific part of the application I'm developing:

This is how the component's logic works:

export class StockStatusComponent implements OnInit{

  articles: Article[] = [];
  selectedLevel: any;

  constructor(private service: ArticleService) {
   }

  ngOnInit(): void {
    this.loadDataFromBackend();
  }


  loadDataFromBackend() {

    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>

Explanation of the code steps:

Upon accessing the component, it should display in the console the "articles" that meet the specified condition. This part seems to be working correctly as it fetches the desired data in the ngOnInit function.

The issue arises when I select an option from the list, such as 'all'. It should fetch all articles, but it only does so after clicking twice. Here's an example to illustrate:

Example:

  1. When entering the component, the array is empty due to no records meeting the condition at that moment.

  2. Selecting the 'all' option should display all records, however, it initially shows the same result as in step 1. To get the desired outcome, I need to click again and re-execute the 'select Level()' method.

I appreciate any assistance provided in advance!

Answer №1

function fetchArticles() {

    console.log("Fetching articles from server...");
    if (this.selectedCategory === "all") {
      this.articleService.getArticles().subscribe(response => {
        this.articles = response;
        console.log(this.articles);
      })
    }
  }

Make sure to place your console log inside the subscribe method to see the fetched articles.

The code in your subscribe block is executed after the first click, so initially the console log may appear empty but it gets populated with data on subsequent clicks. The data is indeed returned from the subscribe function on the first call, just with a slight delay.

It's crucial to grasp the fundamentals of Observables and Promises and how they are utilized within Angular applications.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for deploying an Ionic 4 app on the Firebase console

I'm encountering issues deploying my Ionic app on the Firebase console. Here are the steps I've taken: Created a new Ionic project Ran firebase init and firebase deploy commands Unfortunately, I cannot seem to view the Ionic output after depl ...

Issue when generating Angular production build due to module not being found

I've encountered a problem while building an Angular module with angular cli and calling it in another project. Everything works fine when I run ng serve, but I am facing an error when running ng build --prod: ERROR in ./node_modules/my-module/dis ...

Is there a way to set up the application that consumes an npm module with a private git url to strictly utilize files exclusively from the module's dist folder?

In my angular application, I encountered an issue with angular-cli not supporting the creation of a library. To work around this, I opted to use the popular git project found at https://github.com/jvandemo/generator-angular2-library for creating my library ...

Is there a way for me to store the current router in a state for later use

I am currently working on implementing conditional styling with 2 different headers. My goal is to save the current router page into a state. Here's my code snippet: const [page, setPage] = useState("black"); const data = { page, setPage, ...

Importing Typescript modules by specifying their namespace instead of using a function

I have been working on a project where I needed to generate typings from graphql using the gql2ts library. In the gql-2-ts file, I initially used a namespace import for glob, which resulted in TypeScript showing me an error as intended. I then switched the ...

Encountering issue with POST operation in GraphQL on Angular application integrated with AWS Amplify and DynamoDB

I am in the process of developing a basic Angular application using AWS Amplify with a DynamoDB backend. To handle GraphQL API calls, I utilized the amplify add API command to generate the necessary code. My current objective is to populate a table with ...

Discover how to access and manipulate JSON files in an Angular application using

Currently, I am diving into learning TypeScript with Angular and I'm interested in reading a JSON file. The structure of my JSON file is as follows: { "nb": "7", "extport": "1176",, "REQ_EMAIL": ...

Exploring the depths of Angular2 RC6: Implementing nested modules and routing

Within my application, I have a module called SupportModule which consists of 3 sub-modules: AdminModule, ChatModule, and ContactModule. Each of these modules has its own defined routing structure. The overall structure resembles something like this: htt ...

Performing a series of get requests in Angular 2

There is a configuration service that retrieves specific information from a JSON file. getConfiguration(key) { return this.http.get('./app/config/development.json').map(res => { this.result = res.json(); return this.result[ke ...

Do Angular lifecycle hooks get triggered for each individual component within a nested component hierarchy?

I'm exploring the ins and outs of Angular lifecycle hooks with a conceptual question. Consider the following nested component structure: <parent-component> <first-child> <first-grandchild> </first-grandchild& ...

Why does Angular routerlink display %20 before the id path?

In my quest to showcase messages from a nested collection of messages, I have encountered a peculiar issue. When clicking on the "view" tag within certain cards, I use routerlink to navigate to the intended path where messages are displayed. Strangely en ...

Guide to redirecting to an ASP application using POST data from Angular 5

I'm currently working on integrating a payment gateway into my Angular application. This particular payment gateway is built using ASP. The instructions provided by the payment gateway provider instruct me to submit a form as a POST request to a spec ...

Utilize Moment to retrieve the weekend dates

Currently tackling a date-related issue and feeling stuck. Is it feasible to extract weekends from an array of dates using Moment.js instead of the getDay() method? I'm a beginner in JavaScript. ...

ERROR TS1086: A declaration of an accessor within an ambient context is not allowed. Accessor for firebaseUiConfig(): NativeFirebaseUIAuthConfig

Trying to create a Single Page Application with Angular/CLI 8. Everything was running smoothly locally until I tried to add Firebase authentication to the app. Upon compiling through Visual Studio Code, I encountered the following error message: ERROR in ...

Transmitting messages from a cross-domain iframe to the parent window

In my parent component, I am embedding an iframe from a different domain. The iframe contains a button that when clicked, I need to capture the event and pass it back to the parent component. I have experimented with using window.postMessage and window.ad ...

Verify Angular route path using an interceptor

I have configured a route path like this: { path: 'user/:id/edit/:type', component: UserEditTypeComponent, }, I am trying to access this path from an interceptor using activated routes: constructor(private activatedRoute: ActivatedRout ...

Adding an additional element to an incoming array in Angular/Typescript/RxJS - a step-by-step guide

I recently encountered a challenge in my RxJS code involving the transformation of a list of JSON objects into items for a drop-down list. this.folders$ = this.folderStore.folders$.pipe( map((folders: GdFolder[]) => { const data = folders.map(fold ...

Running AngularJS within an Angular 8 application using ngUpgrade is not supported

Struggling to get my Hybrid Angular application up and running using ngUpgrade according to the documentation. The issue is that no matter what tweaks I make, AngularJS just won't cooperate. When I combine Angular and AngularJS, both applications wor ...

Acquire more followers on Google Plus by leveraging Cordova and Ionic 2

I am new to using Angular2 and Ionic2 for developing Android applications with Firebase. I have successfully integrated Google login using the cordova plugin google plus from Ionic native, which provides me with userId and idToken. Using these values, I a ...

Utilize Azure Functions: Employ the Apollo Azure handler within an asynchronous function

Looking to incorporate some checks before executing the apollo handler function, I attempted to wrap it in an async function. However, when exporting the function as async, it consistently returns an empty response. functions.json { "bindings" ...