Is it better to utilize angular's $interval or a promise to execute code upon completion of an api call?

I am facing an issue with a slow api call in my code.

$http.jsonp(url, {
    params: {
      'client': 'translate_about',
      'alpha': 1,
      'hl': 'en'
    }
  })
    .success(function (data) {
      home.translate.list = data.sl;
      //console.log(data.sl);
    });

The following code block needs to be executed either before or in parallel with the completion of home.translate.list. Therefore, I require another block of code to update when home.translate.list is successfully loaded.

  home.modalOn = function (val) {
    //open modal
    home.isModal = true;
    //this if block must wait for home.translate.list to be ready.
    if(typeof home.translate.list !== 'undefined'){
      home.activePageSelection = home.translate.list[val];
      //call wikipedia and get data
      home.callWiki(home.translate.list[val]);
    }
  };
  $scope.$watch(function () {
    return location.hash
  }, function (value) {
    var currentRouteParam = value.split('/').slice(-1)[0];

    if (currentRouteParam !== '') {
      home.modalOn(currentRouteParam);
    } else {
      home.modalOff()
    }

  });

Question:

Is there a way to ensure that home.translate.list is defined before running the if block without including it in the $http.success block?

Answer №1

Here is a suggestion for you:

if (currentRouteParam !== '') {
    var interval = $interval(function() {
        if (typeof home.translate.list !== 'undefined') {
            $interval.cancel(interval);
            home.modalOn(currentRouteParam);
        }
    }, 500);

}

Note:

Make sure to include the $interval service in your controller

Answer №2

It's a good idea to encapsulate the watch functionality within its own function and then invoke that function inside the success block.

.success(function (data) {
    home.translate.list = data.sl;
    watchHash();  
    //console.log(data.sl);
});

function watchHash() {
    $scope.$watch(function () {
    ...
}

Answer №3

To optimize your code in the vm, you can store the promise for the translation instead of the list:

home.translatePromise = $http.jsonp(url, {
    params: {
      'client': 'translate_about',
      'alpha': 1,
      'hl': 'en'
    }
  })
  .then(function (response) {
      return response.data.sl;
  });

Make sure to reference the promise and not the raw value:

home.modalOn = function (val) {
  //open modal
  home.isModal = true;
  //This conditional block should wait for home.translate.list to be ready.
  home.translatePromise.then(function(list){
    home.activePageSelection = list[val];
    //Retrieve data from Wikipedia
    home.callWiki(list[val]);
  });
};

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

Can you explain the distinction between employing express.urlencoded() with extended set to true as opposed to setting it to false along with performing manual JSON stringify/parse calls?

Within my NodeJS/Express server, I am faced with the decision of setting extended to either true or false for the urlencoded middleware: app.use(express.urlencoded({ extended: true/false })); I have come to understand that when set to false, it signifies ...

How can Angular.js directives help display various nested data structures?

Is there an Angular.js directive available for displaying nested JSON data dynamically as a view without prior knowledge of the structure? Let's say we have the following JSON resource at a REST endpoint /api/orgranisations/:organisation_id/: { ...

Having trouble setting the selected option for a select element using the $get method in jQuery?

I'm struggling with setting the selected value of a select option using AJAX, particularly the $get function of jQuery. I've been trying to make it work, but for some reason, setting the textbox is successful while setting the select option isn&a ...

Having trouble understanding how to display an HTML file using Next.JS?

Currently, I am working on a project that involves utilizing Next.JS to develop a webpage. The main goal is to display a PDF file on the left side of the screen while integrating Chaindesk on the right side to create a chat bot capable of extracting inform ...

Encountering errors while attempting to share files in a system built with Node.js, Express,

This snippet shows my Node.js code for connecting to a database using Mongoose const mongoose = require('mongoose'); function connectDB() { // Establishing Database connection mongoose.connect(process see your Naughty's you're sure ...

Prevent users from inserting images from their desktop into the HTML by disabling

While working on a HTML5 drag and drop image uploading feature, everything was going smoothly. I had a small div in the HTML with a JavaScript event handler set up like this: $('#uploader').on('dragover', function(e){ ... }).on(&apos ...

Tips for sending a form with the <button type="submit"> element

I created a login form and initially used <button type="submit">, but unfortunately, it was not functioning as expected. However, when I switched to using <input type="submit">, the form submission worked perfectly. Is there a JavaScript method ...

Is there an alternative solution to the issue of the jQuery resize() event not triggering when an input is

Despite the fact that the jQuery event resize() should trigger when the width of an input box changes, it seems to be malfunctioning. As per the jQuery API documentation, the resize event is supposed to go to the (window) handler. So my query here is, what ...

How to iterate dynamically over arrays using JavaScript

I am working on a JavaScript project where I need to create a graph with 25 different data points. While my current JavaScript method is effective, I am facing an issue - I have multiple arrays and I am looking for a solution that allows me to use a for lo ...

Invalid POST Request Triggering 400 Error in Django with Ajax Communication

I have been through numerous discussions on various forums about this issue, but I am unable to make my form submit successfully; it always results in a 400 (Bad Request) error in the console. I have tried everything I could think of at this point, too ma ...

Angular ng-show failing to execute condition

I tried running this code in ng-repeat, but the conditional inside ng-show doesn't seem to be working. Even after moving it out, I still can't get it to work. The expression is displaying now_playing but won't hide or show the element no ma ...

Improving user input in AngularJS

My goal is to create a filter that converts time into seconds, such as: 01:30:10 becomes 5410, and vice versa. This way, the model only holds seconds while providing users with a more user-friendly representation. I've successfully implemented a work ...

The JSON.stringify method may not accurately reflect the original object that was converted into a string

Working on a Connect Four app for my school project has been an interesting challenge. At the moment, I am grappling with JSON.stringify and trying to encode an object that holds a two-dimensional array of "hole" objects to eventually send it to the server ...

Why won't the div move when I click it?

Could you please explain why my JavaScript code isn't functioning as expected? The intended behavior is for the 'mark' div to move to the current mouse coordinates upon clicking within the map. ...

Is it possible to modify the location of my CSG object prior to performing subtraction in Threejs with ThreeCSG?

Looking to carve out specific "voids" in platforms using ThreeCSG. The goal is to have these voids positioned at particular locations on the larger platform. var geometry = new THREE.CubeGeometry( 500, 10, 500 ); var hole_geometry = new THREE.CubeGeom ...

Is there a way to seamlessly inject a stylesheet into a React application without causing any flickering or reloading on the website?

In my React application built with next.js, I am fetching a stylesheet via a GET request and appending it to the webpage. However, whenever this stylesheet is loaded in, the elements impacted by it re-render unnecessarily, even if there are no actual chang ...

Error: Conversion of "2018-01-01-12:12:12:123456" to a date is not possible for the 'DatePipe' filter

<td>{{suite.testSuiteAttributes && suite.testSuiteAttributes.modifiedTimestamp | date: 'yyyy-MM-dd' }} </td> I am trying to display the date in the "05-Feb-2018 11:00:00 PM CST" CST format, but I keep getting an ...

Tips for updating specific properties of an object within a MongoDB database using arrays

I have encountered a problem with updating only specific properties of an object in my MongoDB database. While the query I'm using is working for most variables, it unexpectedly sets certain arrays (media: [] and sports: []) in the athleteProfile back ...

Updating the route in Express.js/Node.js to redirect form submission from `/page` to `/page/<input>`.Is this fine for you

How can I redirect a user from /page to /page/:nickname in Express after they enter a nickname and click submit? This is my code: // app.js app.get("/page", (request, response) => { response.render("page"); }); app.get("/page/:nickname", (reques ...

What are the benefits of utilizing AJAX paging versus jQuery paging in my web application?

I have implemented paging using the following code: <script type="text/javascript"> function goToPage(pageIndex) { $("#currentPage").val(pageIndex); $("#gridAction").val("CurrentPageChanged"); ...