Angular component initialization problems

Hey everyone, I'm encountering a small issue. I am attempting to retrieve some images from Flickr using their API, but for an unknown reason, the list is not populating at the desired time. Below is my code for better clarification.

This is the code snippet:

Component:

export class MainComponent implements OnInit {

  myArray: Item[] = [];
  randomItem: Item;

  constructor(private dataService: DataService) {
  }

  refresh(){
    console.log("[refresh()]:",this.myArray.length)
    var selected = Math.floor(Math.random() * this.myArray.length);
    this.randomItem = this.myArray[selected];
    this.myArray.splice(selected,1);

  }

  ngOnInit() {
    this.dataService.getImages().subscribe(res => {
      this.myArray = res.items;
      console.log("[ngOnInit]:" ,this.myArray.length)
    })

    console.log("[ngOnInit 2]:",this.myArray.length)
    if(this.myArray.length>0){
      var myInterval = setInterval(this.refresh(), 1000);
    }else{
      clearInterval(myInterval);
    }
    }

}

Service:

export class DataService {


 imagesUrl = 'https://api.flickr.com/services/feeds/photos_public.gne?format=json&nojsoncallback=1';
  myArray:Item[]=[];
  randomItem:Item;

  constructor(private http: HttpClient) {
  }

  getImages(): Observable<Flickr>{
    return this.http.get<Flickr>(this.imagesUrl);
  }

}

Output:

[ngOnInit 2]: 0

[ngOnInit 1]: 20

It's clear from the component code that my Interval function is never executed. It seems like the array doesn't have enough time to initialize itself. Why isn't it working as expected? What steps can I take to rectify this issue?

Please note that this question is unique since the problem persists even with the interval not functioning correctly either way.

Answer №1

Prior to receiving a response, the code is being executed. To rectify this issue, the interval code should be relocated inside the response block -

private interval;

  refresh(){
    console.log("[refresh()]:",this.myArray.length)
    var selected = Math.floor(Math.random() * this.myArray.length);
    this.randomItem = this.myArray[selected];
    this.myArray.splice(selected,1);

    if(this.myArray.length == 0){
       clearInterval(this.interval);
    }
  }

    ngOnInit() {
        this.dataService.getImages().subscribe(res => {
          this.myArray = res.items;
          console.log("[ngOnInit]:" ,this.myArray.length)

           this.interval = setInterval(() => {
              this.refresh(); 
           }, 1000);

        })

    }

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

How can I use JavaScript to retrieve information from a different webpage?

I am trying to extract data from another webpage using JavaScript, jQuery, or Ajax without using PHP. I came across a helpful example on Stack Overflow (link here). However, when I implement these codes in my index.html file, it doesn't seem to work. ...

Steps to access the most recent eventName (determined by date)

I am working with two arrays var events=["DELIVERED", "OUT TO DELEVERY", "REACHED WAREHOUSE", "DEPARTED"]; var eventDetails= [{ "source" : "application" "DateTime": "2016-05-12 11:20:00", "eventName" : "DELIVERED" }, { "source" : "application" "DateTime" ...

Tips for updating an input field using JavaScript

Here is a simple code snippet that I have written. <script language='javascript"> function check() {} </script> <div id="a">input type="text" name="b"> <input type="button" onClic ...

Struggling to retrieve the ID from the API within the Angular and .NET Core component

Currently, I am working on a test project to enhance my knowledge of Angular. However, I have encountered an issue where the student's id fetched from the service is null. To handle the data, I have implemented a StudentController. Below is a snippet ...

Update the page content once the popover is closed. Working with IONIC 3

In my application, there are 4 tabs, each displaying different data based on a specific configuration. The header of the page includes a popover component with settings options. When a user adjusts the settings and returns to a tab page, the content on th ...

Can Regex expressions be utilized within the nodeJS aws sdk?

Running this AWS CLI command allows me to retrieve the correct images created within the past 45 days. aws ec2 describe-images --region us-east-1 --owners self -- query'Images[CreationDate<`2021-12-18`] | sort_by(@, &CreationDate)[].Name&apos ...

Persistent extra pixels found in CSS radiobutton group buttons that persist despite attempts to remove them

UPDATE: I have corrected the title of this post, as it was mistakenly taken from another post. For the past few months, I've been working on a sports app using React. However, I am facing a minor cosmetic problem with my radio buttons. Despite my eff ...

Implementing Constants in Angular 2: Best Practices

Within my Angular 2 project, I have a crucial object known as translation that stores various strings utilized in multiple forms. This global configuration appears as follows: public translator = { 'performance_standard_time_deviation&apo ...

Should all pages in React be rendered on the server side?

Currently, I rely on Next.js for implementing server-side rendering on my React website. At the moment, I have implemented server-side rendering across almost all pages of the site, including profile information and other content that requires a login to ...

Tips for receiving a success notification post form submission on CodeIgniter

I'm currently working on a form using CodeIgniter. Below is the code I have so far: <?php echo form_open_multipart(''); ?> <div class="input-group"> <input maxlength="30" type="text" name="name" placeholder="Name" class ...

Troubleshooting minified JavaScript in live environment

Trying to wrap my head around AngularJS and Grunt. In my GruntFile.js, I have set up two grunt tasks for development and production. In production, I am using uglification to combine multiple js files into one. I am in need of some advice or tips on how t ...

Retrieving data from a string and storing it in a database

I am working with multiple columns represented by <ul> elements that can be sorted using jQuery UI. In order to save the positions of the <li> items within these <ul> elements, I need to serialize the data. $(function() { $("ul.sortable ...

Manipulating data rows in a table using jquery

I have a button called #add that, when clicked, adds a new row to a table. The last cell of the newly inserted row contains a delete icon that, when clicked, should remove the entire row. I thought I had everything set up correctly, but for some reason, c ...

Struggling with AJAX requests in a cordova/ratchet app for mobile devices

I encountered some challenges when trying to make an AJAX request in my cordova project. $.ajax({ url: "https://mydevserver/REST.php?method=mobileGetData", success: function(result){ alert("successful ajax"); }, error: function(xhr ...

Express: SimpleAuth

I've been attempting to set up basic authorization for the endpoints in my express app using express-basic-auth, but I keep getting a 401 unauthorized error. It seems like the headers I'm sending in Postman might be incorrect: Middleware: app.u ...

"Step-by-step guide on deactivating SmartyStreets/LiveAddress with an onclick function

I've recently taken over a SquirrelCart shopping cart application that utilizes SmartyStreets/LiveAddress code, and I'm struggling to figure out how to disable the verification process when copying billing address fields to shipping address field ...

The data received from the API mapping resulted in non-existent information

Currently, I am attempting to extract a specific value from the API response by mapping an array. Once I receive the complete response, the data is clearly defined. EmissionByPolluant(url:string):Observable<emissions[]>{ return this._http.get(url) ...

Having trouble rendering JSON data on a FlatList component in React Native

After expanding FlatList in console.log and verifying the JSON value, I am facing an issue where the values are not displaying on the list. The data is being passed to the second screen and displayed there, but the first screen remains blank. Any assistanc ...

Enhance jQuery for a dynamic navigation dropdown with multiple sub-menus

Looking for help with a jQuery script as I am a beginner in using jQuery. jQuery(document).ready(function ($) { $(".sub-menu").hide(); $(".current_page_item .sub-menu").slideDown(200);; $("li.menu-item").click(function () { if ($('.sub-menu&apos ...

What is the best way to programmatically click on each list item without triggering their normal behavior and silently loading their content instead?

I am looking to programmatically click on a series of unordered list items without showing the results of the clicks. The goal is to preload dynamic content such as images and text that would normally be loaded and displayed upon clicking on the list items ...