Fetching data from a URL using AngularJS while the view is being loaded

Struggling to perform an API call when loading a specific view.

controllers.controller("detailsCtrl", ["$scope", "$routeParams", "$filter", "$http", function($scope, $routeParams, $filter, $http) {

  $scope.getCurrent = function(url, id, callBack, apiCall, promise) {
    var url = "api.openweathermap.org/data/2.5/weather?id=2172797";
    var id = "&appid=d436c04d23a5a44329eb8255190a84be";
    var callBack = "&callback=JSON_CALLBACK";
    var apiCall = url += id += callBack;
    var promise = $http.jsonp(apiCall);
    promise.success(function(response) {
      $scope.current = response.current;
      console.log($scope.current);
    });
  };

  $scope.cityName = $filter("filter")($scope.data.list, {
    id: $routeParams.cityId
  })[0];

}]);

utilizing ng-init within the html

<div ng-controller="detailsCtrl" ng-init="getCurrent()">
<h1>{{ cityName.name }}</h1>
<tr>
<td>lat: {{cityName.coord.lat}}, lon: {{cityName.coord.lon}}</td>
<td>{{}}</td>
<td>{{}}</td>
<td>{{}}</td>
<td>{{}}</td>
<td>Clouds: {{cityName.clouds.all}}</td>
<td>{{}}</td>
<td>{{}}</td>
</tr>

</div>

Continuously receiving: http://localhost:8080/api.openweathermap.org/data/2.5/weather?id=2172797&appid=d436c04d23a5a44329eb8255190a84be&callback=angular.callbacks._1 , any insights on why?

note Additionally attempting another API call in the mainview prior to the user navigating to the detailed view. Tried using ng-click when transitioning views, but it did not trigger the call at all.

Answer №1

While I prefer using angular2 over angularjs, it seems like your issue might stem from an incorrect http request. To illustrate, I've put together a sample in a plunkr: http://plnkr.co/edit/FjGewEhLpkaOlPRN?s=preview

fetchData: function () {
          var obj = {};
          var jsonData = JSON.stringify({ obj: obj }); //For POST
          var req = {
              method: 'POST',
              url: 'http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=d436c04d23a5a44329eb8255190a84be',
          };
          return this.http.post(req.url, req.data, req)
          .toPromise()
          .then(function (response) {
              return response;

          });
      }

It's possible that the relative URL in your solution is causing issues.

I hope you find this information helpful.

Thank you!

Answer №2

Can you kindly update the URL according to the following:

var url = "http://api.weather.org/data/2.0/forecast?id=2172797";

Since you are having trouble locating the correct URL, this change will ensure that the URL is automatically generated based on the current webpage's URL.

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

CodeIgniter session not being updated after AJAX call

What could be the reason for CodeIgniter session not updating values after an AJAX request? Controller index: public function index() { $this->session->set_userdata( 'greetings', 'hello!' ); } AJAX request: $.ajax({ ty ...

Is there a way to control the playback of a video, such as

Currently, I am involved in a project related to IPTV. One of my objectives is to be able to capture the moment at which a video is paused so that when clicking on another button, a small iframe opens with the same video continuing from where it was origin ...

Ways to preserve decal placement using Three.js

I am searching for a solution to store and reload the decals generated in this example (source code). The goal is to allow users to save a new splatter they paint and then reload it at a later time. I have attempted various methods, but none have been succ ...

Variables in an Angular application are not appearing in the HTML rendering

Currently learning AngularJS as I develop a web application. After going through tutorials, I started with a basic list but am baffled as to why my browser only shows {{title}}. In my app.js module, here's the snippet where I defined the controller: ...

Functionality of local data storage

I'm currently exploring the capabilities of the localStorage feature. Let's say I have a large JSON object stored using localStorage. I need to share this data with the testing team for review. However, if I try to display the stored data on an H ...

Angular2 - Utilizing Promises within a conditional block

I'm currently facing an issue where I need to await a response from my server in order to determine if an email is already taken or not. However, I am struggling to achieve this synchronously. TypeScript is indicating that the function isCorrectEmail( ...

Utilizing Firebase login to integrate with Facebook API

My current setup involves Facebook authentication tied to login, all managed through Firebase. However, I now face the need to make an API call to Facebook using 'me/friends/' endpoint without having to send another request since I am already log ...

Table cell featuring a status menu created with Material UI DataGrid

I'm looking to include a column called "Filled Status." Although I've checked the documentation, I can't quite figure out how to do it. It seems like I may need to use renderCell when setting up the column, but I'm not sure how to make ...

Adjust the transparency and add animation effects using React JS

When working on a React project, I encountered an issue where a square would appear under a paragraph when hovered over and disappear when no longer hovered. However, the transition was too abrupt for my liking, so I decided to implement a smoother change ...

JavaScript: Scroll Through Images Horizontally with Descriptions for Each Image

I am looking to create a horizontal scroller/slider that will display images with captions underneath each image. The data is provided in an array of objects, so I need to iterate through the data and populate each item in the scroller with the necessary i ...

How to update a nested object within an array in mongoose by referencing its specific id

Here is a glimpse of my database where I am looking to update an object within the perDayDetails array using its unique identifier in Mongoose. "_id":{"$oid":"612f45863106a21bc0506a36"}, "fullname":"abc xyz" ...

What are the proper methods for accurately testing vuex state and mutations?

Can someone guide me on how to properly test mutations and state? I have a modal window component that is rendered when the showModal property in the state is true. There is an event triggering a mutation that changes this property. How can I verify that a ...

Issue with Achieving Two-Way Binding in Angular 1.5 Component when using $ctrl

I am struggling with customizing some products using a component in my index.html. Ultimately, I need to calculate the total of selected products within the main controller "planosVoz" using two-way binding on the svaTotal property in the component control ...

Conditional rendering with React.js in the DOM

Just starting out with React and encountering an issue with rendering using reactDom: index.js import ReactDOM from 'react-dom'; import A from 'components/A'; import B from 'components/B'; render(<A />, document.getEl ...

Unable to view through transparent merged geometry in three.js

Could someone assist me in understanding why, when merging the geometries of these boxes, I am encountering visibility issues from certain angles? Blue boxes represent normal individual boxes, while Orange boxes are the result of merged geometries. I am u ...

Mongoose is having trouble identifying the 2dsphere index I created

I am currently attempting to add a 2dSphere index for the field startLocation within the tourSchema. This is how it is defined: startLocation: { type: { type: String, default: 'Point', enum: ['Point'] ...

Tips for preventing the collapse of a table row using a button?

I have implemented a Bootstrap collapse feature on my table row. Currently, the collapse can be triggered by clicking anywhere on the row, which is working as intended. However, I would like to make one exception - if the user clicks on the desktop icon i ...

Error: Reading the property 'any' of an undefined object resulted in a TypeError after an update operation

After updating multiple npm packages in my application, I encountered a series of errors that I managed to resolve, except for one persistent issue! TypeError: Cannot read property 'any' of undefined at Object.<anonymous> (/home/cpt/Deskto ...

What is the best way to swap out the if else statement with a Ternary operator within a JavaScript function?

Is there a way to replace the if else statement in the function using a Ternary operator in JavaScript? private getProductName(productType: string): string { let productName = 'Product not found'; this.deal.packages.find(p => p.isSele ...

Module fails to load in the proper sequence

As a .NET developer who is relatively new to modern client-side web applications, I am currently working on developing an Angular2 charting application using Chart.js. The modules are being loaded with SystemJS. Below is the content of my systemjs.config. ...