Koen De Couck Koen De Couck - 6 months ago 30
AngularJS Question

Simple http.post with angular-fullstack (using ui-router)

Context: I just got started with AngularJS, starting from a clean generator-angular-fullstack build. As part of the install I went with UI router.
I've set up server API endpoints and tested them in the browser. They all check out.

I'm trying to do a minimal http.post request to call those API endpoints. Via Yeoman I've pre-generated a new route 'signIn' in client/app/signIn (which includes signIn.html, signIn.js, signIn.controller.js, signIn.controller.spec.js, signIn.scss).

Here is what I'm working from:

signIn.html

<script>
var MainCtrl = function($scope, $http) {
$http.post('/api/auth/signin', {auth_token: '5'}).success(function(response) {
$scope.response = response;
});
};
</script>
<body ng-controller="MainCtrl">
<section ui-view>Response: {{response}}</section>
</body>


For completeness (still untouched:)

signIn.js

'use strict';

angular.module('orbitApp')
.config(function ($stateProvider) {
$stateProvider
.state('signIn', {
url: '/signIn',
template: '<sign-in></sign-in>'
});
});


signIn.controller.js

'use strict';
(function(){

class SignInComponent {
constructor() {
this.message = 'Hello';

}
}

angular.module('orbitApp')
.component('signIn', {
templateUrl: 'app/signIn/signIn.html',
controller: SignInComponent
});

})();


I've tried a number of variations on the signIn.html script, no luck so far. I'd like to find the 'native' way to do it, so I'd rather not use jquery. Any advice would be appreciated!

Answer

I don't understand exactly what you're trying to do but I hope this code will help you :

signIn.html

<body>
<section ui-view>Response: {{response}}</section>
<a class="btn btn-info" href="#" ng-click="callingPostFct()" role="button">Trigger http post using button as example</a>
</body>

signIn.js

'use strict';

angular.module('orbitApp')
  .config(function ($stateProvider) {
    $stateProvider
      .state('signIn', {
        url: '/signIn',
        template: '<sign-in></sign-in>'
      });
  });

signIn.controller.js

'use strict';
(function(){

  class SignInComponent {
    constructor($scope, $http) {
      $scope.callingPostFct = function() {
        $http.post('/api/auth/signin', {
          //do anything you want with your api endpoint here :
          auth_token: '5'
        }).success(function(response) {
          console.log('post successfully worked !');
          $scope.response = response;
        });
      };

    }
  }

  angular.module('orbitApp')
    .component('signIn', {
      templateUrl: 'app/signIn/signIn.html',
      controller: SignInComponent
    });

})();

Note : Don't put ng-controller="" in your html files because they are already called by the generator and they will be called twice or even more which could produce some trouble in your app and reduce performance also.

In most of case, when you're trying to use <script> tag, you can do it in the controller.