0

I am trying to have one very simple CRUD app. It involves one form with single text box. and all the entries posted through box shall display in a grid below text box.

All is well but somehow grid doesn't update with new entry unless page is refreshed. I am using loopback api running on localhost:3000 and my angular app on localhost:9000. Database is MySQL.

Same code works as expected if I am using MEAN stack. Now we have to support mySQL and decoupled API from my application. This is controller.

    angular.module('dashboardApp')
      .controller('StateCtrl', function ($scope, $http) {
         $scope.formData = {};
         $scope.baseUrl = '//localhost:3000/api/v1/states';

         $http.get($scope.baseUrl).success(function(states) {
           $scope.states = states;
         });

        $scope.create = function() {
          $http.post($scope.baseUrl, $scope.formData)
            .success(function(states) {
              $scope.states = states;
            })
            .error(function(states) {
              console.log('Error: ' + states);
           });
        };
     });

This is view.

    <form class="form-inline" role="form" data-ng-submit="create()">
      <div class="form-group">
        <label class="sr-only" for="name">State</label>
        <input type="text" class="form-control" id="name" placeholder="Enter state"  ng-model="formData.name">
     </div>
     <button type="submit" class="btn btn-default">Enter</button>
    </form>

    <table class="table table-striped">
  <tr ng-repeat="state in states">
        <td>{{state.name}}</td>
  </tr>
    </table>

Any help is appreciated. just a note: I've tried using services/resources as well instead of $http.

2
  • console.log(states) and see what is logged right out of you submit the form Commented Dec 30, 2013 at 12:56
  • console.log("states " + JSON.stringify(states)); returns states {"name":"new entry","id":27} Commented Dec 30, 2013 at 13:25

3 Answers 3

2

I think the problem here is that $http.get is returning an array and $http.post in the $scope.create function is returning a single object.

  1. You have to push the returned object into the $scope.states array. Or ..
  2. Return an array from the $http.post request and assign it to $scope.states

    angular.module('dashboardApp') .controller('StateCtrl', function ($scope, $http) { $scope.formData = {}; $scope.baseUrl = '//localhost:3000/api/v1/states';

     $http.get($scope.baseUrl).success(function(states) {
       $scope.states = states; // this returns an array
     });
    
    $scope.create = function() {
      $http.post($scope.baseUrl, $scope.formData)
        .success(function(states) {
          //$scope.states = states; // this return an object
          // Do this
          $scope.states.push(states);
        })
        .error(function(states) {
          console.log('Error: ' + states);
       });
    };
    

    });

NB: Or you could just return the whole array on $http.post

Sign up to request clarification or add additional context in comments.

2 Comments

ahhhhh, what a relief. I can't thank you enough. Although I couldn't understand why very same code works under MEAN stack? Thanks everyone for kind and quick support.
Well I revisited my mongo code, and after careful analysis it turned out I am returning whole array after creating new entry (as pointed by you @dcodesmith ), so it answers everything.
0

As you are doing Cross-Origin Resource Sharing (CORS) is the API service adding the required HTTP Access-Control-Allow-Origin header? If not the response will be blocked by the browser. Adding an error callback to your $http.get() should also help detect what is wrong.

2 Comments

Following is CORS header as returned. Error handler in http.get is also working fine, no error. Infact everything works it's just grid doen't update without refresh. Access-Control-Allow-Origin →*
That is the correct header so no problem there. Another thing that might be causing an error is caching. If the server is not specifying caching headers it is up to the browser to decide if requests get cached or not. With Fiddler you can check if the request is actually send to the server. Don't trust the browser network reporting as it can show a request as being returned from the server while it was actually cached.
0

I concur with @Maurice that you might be running into a cross domain issue you have two ports involved 9000 and 3000. If the data you are expecting back is in json you can try adding this your url

$scope.jsonpUrl = $scope.baseUrl+"?callback=JSON_CALLBACK";

$http.jsonp($scope.jsonpUrl)
.success(function(states) {
    $scope.states = states;
})
.error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
    console.log("Error:", data);
});

Give it a try and let us know. Cheers

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.