Using Restangular with the same URL but different files - javascript

I need to communicate with a REST web service via Angular and I'm using RestAngular but I'm running into some difficulty. I have to use the same URL but GET & POST to two different files. I'm setting the base URL in my .config in the app.js and the service.js is where I'm setting the other URL via RestangularConfigurer. The BaseURL in the config has a query string appended to it. The second URL in the service does not. I want to GET from the BaseURL in the config and POST to the Factory from an input. Below is an example of my code
app.js
'use strict';
angular
.module('testApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'ui.bootstrap',
'ngGrid',
'google-maps',
'ngMessages',
'restangular'
])
.config(function (RestangularProvider, $routeProvider) {
RestangularProvider.setBaseUrl('http://dev.domain.com:9005/question-ws.htm?&areacode=215');
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
});
service.js
'use strict';
angular.module('testApp')
.factory('NextRestangular', function($http, $sce, Restangular){
return Restangular.withConfig(function(RestangularConfigurer) {
RestangularConfigurer.setBaseUrl('http://dev.domain.com:9005/next-question-ws.htm');
});
});
controller.js
'use strict';
angular.module('testApp')
.controller('ScreenCtrl', function ($scope, Restangular, NextRestangular) {
Restangular.all().getList();
NextRestangular.all().getList();
});
I can't seem to GET from Restangular and I can't POST to NextRestangular. Will the file structure be able to support this? Am I going about this all wrong?

Restangular is a service to handle Rest API Restful Resources.
The .htm in your URLs leads me to believe the response is not JSON. I don't believe Restangular will work for you if that is the case. I recommend looking into ngResource or even $http. If your response is JSON, the following should help get you on your way.
In this example, the baseUrl should be "http://dev.domain.com:9005".
RestangularProvider.setBaseUrl('http://dev.domain.com:9005');
I have not used setRequestSuffix before but that may allow you to also have the .htm.
RestangularProvider.setRequestSuffix('.htm');
Then your API calls should look something like this.
Restangular.all('next-question-ws').get({areacode: 215});
Restangular.all('next-question-ws').post(
// JSON Payload here.
});

Related

Laravel mix and AngularJs

I'm trying to use Laravel Mix, which runs webpack, to compile an angular app into one file. I get the error:
Uncaught ReferenceError: app is not defined
my webpack.mix.js:
const { mix } = require('laravel-mix');
mix.js('resources/assets/js/dependencies.js', 'public/js')
.sass('resources/assets/sass/app.scss', 'public/css');
my bundle.js :
//load angular
require('angular');
//Load Angular's plugins
require('angular-ui-router');
//Init Angular app
require('./app/app');
//Load angular controllers
require('./app/Controller/aboutController');
....
//Load angular directive
require('./app/Directive/directive');
//Load angular services
require('./app/Services/AccountService');
....
My app/app.js:
var app = angular.module('app', ['ui.router']);
app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function ($stateProvider, $urlRouterProvider, $locationProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'app/View/homeView.html',
controller: 'homeController'
})
...
}]);
app.run(['$state', '$rootScope', function ($state, $rootScope) {
//APP RUN
}]);
I get the Uncaught ReferenceError: app is not defined when I call app.controller(), for example app/Controller/aboutController.js:
app.controller("aboutController", ['$scope', '$rootScope', '$http', function ($scope, $rootScope, $http) {....}
Am i missing something? If i load all the file one by one using html it works fine.
If you are defining your app's controller in separate file , then you cannot use directly app as there is no reference . You first have to refer to the module .
angular.module('app')
.controller('aboutController'....
Let me know if this work for you.
For anyone looking to do this in a more automated way for their next Laravel project, I created an article to explain how. Tested on Angular versions 4-7 with Laravel versions 5.4-5.8. I hope it helps!

AngularJS [$injector:unpr] Unknown provider: dataProvider <- data <- PageCtrl

I have seen the other answers and so far nothing has helped me. I get this error with the following code in a file:
angular.module('myApp.page', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/page/:pageId', {
templateUrl: 'page/view.html',
controller: 'PageCtrl',
resolve: {
data: function($q, $http, $routeParams) {
var deferred = $q.defer();
$http({method: 'GET', url: 'http://....' + $routeParams.pageId})
.then(function(data) {
deferred.resolve(data);
});
return deferred.promise;
}
}
})
}])
.controller('PageCtrl', function ($scope, $rootScope, data) {
//do stuff
}
And in the app.js I have this:
angular.module('myApp', [
'ui.bootstrap',
'ngRoute',
'ngTouch',
'ngResource',
'myApp.page'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/'});
}]).
config(['$provide', Decorate])
Everything was working correctly and I fetched the data with the HTTP method with no problems, until I started using the Q library and moved the data fetching into the config section. Any tips? None of the other answers seem to work. Thanks in advance!
You issue is due to the fact that you are using ng-controller directive to instantiate the controller PageCtrl which takes a dynamic dependency data which is only created by the router. So when you inject a dynamic dependency via router resolve and having the router instantiate the controller, you do not need to and should not instantiate the controller via ng-controller it will simply fail due to the lack of dependency availability from the injector. router will manage the instantiation of the controller and setting it up for the respective view for you.
So just remove ng-controller from your view also make sure the partial represented by the route is complete enough to represent the view related to the controller functionality. Also i have seen it is a good practice not to start with a partial view with ng-controller and instantiate with route which will help making that partial view more reusable with a different controller. Also while creating a unit test you can easily mock the dynamic dependency and feed it via the $controller service.

AngularJS - How to refer to a submodule controller from ui-router?

I'm struggling a bit with having submodules in an Angular 1.3.9 app. I've got a (non-working, sorry) preview at http://plnkr.co/edit/XBfTPAGRRe0CWJgjGJzc?p=preview and I think it's freaking out, in part, because I'm using Restangular.
I have the following:
angular
.module('estimate', ['ui.router', 'restangular', 'estimate.project'])
;
angular
.module('estimate.project', ['ui.router'])
.config(['$stateProvider', '$urlRouterProvider', '$locationProvider'
, function($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider
.state('project', {
url: "/project/{id:int}",
abstract: true,
templateUrl: '/app/templates/project.html',
controller: "ProjectController as project",
resolve: { // stuff }
})
.state('project.overview', {
url: "",
templateUrl: "/app/templates/overview.html"
})
// ...
;
}])
.controller('ProjectController', ['$scope', 'ProjectService', 'myProject'
, function($scope, ProjectService, myProject) {
console.log('i made it!');
}]);
And in my template, which is served from the estimate module, I have:
<li><a ui-sref="project.overview({ id: 1 })">One</a></li>
The URL resolves correctly on the page, but clicking on it does nothing. It doesn't even throw any console errors - it just sits there. My gut tells me it has to do with how I'm referring to the controllers and/or the routes, and if they need to be prefixed or modified to work with a submodule. Any ideas on how to get it to load properly?
If this post is too scatterbrained, let me know and I'll try to clean it up.
I updated your plunker here and would say, that the most important change is - referencing sub-module in the main module:
Instead of this:
angular
.module('estimate', ['ui.router', 'restangular'])
...
angular
.module('estimate.project', ['ui.router'])
...
We have to use this, i.e. reference sub module in a parent module
angular
.module('estimate', ['ui.router', 'restangular', 'estimate.project'])
...
angular
.module('estimate.project', ['ui.router'])
...
With some few other small adjustments, that should be the way. Check it working here

$routeProvider.when(..) not catching all URLs

setup: jade, angular, express, node.
In my routeProvider of angular, I am having some issues. I am requesting a url with a parameter which it is not catching.
var app = angular.module('myApp', ['ngRoute']);
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
//... omitted some url/pages here
//start of SPA
.when('/dashboard/', {
templateUrl: 'partials/index',
controller: 'dashIndexCtrl'
})
.when('/dashboard/class/:id',{
templateUrl: 'partials/class',
controller: 'classCtrl'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
}]);
When I call localhost/dashboard/class/TEST
I get redirected to root.
I declare my routes on the server side as follows:
app.get('/dashboard', routes.dashboard);
app.get('/dashboard/partials/:name', routes.partials);
app.get('/api/class/:id', api.classGet);
My controller name matches up with the routeProvider. In which case the controller code goes as follows:
app.controller('classCtrl', function($scope, $http, $routeParams){
$http.get('/api/class/' + $routeParams.id)
.success(function(dataJson){
console.log(dataJson);
});
});
Why is routeProvider missing this url? I have set breakpoints within my controller so I am certain it is not being called. Also my partials/class.jade is not being called. Let me know if you need anymore code or directory information. Thanks in advance.
After further investigation:
If I go: localhost/dashboard/partials/class it will load that jade file. So it is definitely the controller.
Directory structure, I believe this is my issue now....
+---\
| +---\views
| +---index.jade
| +---dashboard.jade
| +---\partials
| +---index.jade
| +---class.jade
Take a look into console and observe that AngularJS tries to load templates from /partials/index then from /dashboard/partials/index
Solution
set templateUrl path as /dashboard/partials/index in config section.
Reason: angular-route.js
templateUrl = $sce.getTrustedResourceUrl(templateUrl);
if (angular.isDefined(templateUrl)) {
next.loadedTemplateUrl = templateUrl;
template = $http.get(templateUrl, {cache: $templateCache}).
then(function(response) { return response.data; });
}
There is no concatenation templateUrl with route path – just load tempalteUrl from Angular root of application.

How to use url parameters in angularjs, ui-router and $stateParams

I have followed the instructions from https://github.com/angular-ui/ui-router/wiki/URL-Routing
but cannot get this to work properly.
I have the following:
var application = angular.module('application', ['ui.router']);
application.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {
$urlRouterProvider.otherwise("/test");
$stateProvider
.state('index', {
url: "/test/:param",
templateUrl: "App/Test.html",
controller: function ($scope, $stateParams) {
alert($stateParams.param);
}
});
$locationProvider.html5Mode(true);
});
Without the /:param this works as you would expect - i.e. the ui-view is correctly populated with Test.html. However, whenever I put the /:param in I get an error. The error is:
GET http://localhost:3880/test/App/Test.html 404 (Not Found)
App is the route of my angular stuff and Test.html should have a path of
http://localhost:3880/App/Test.html
which it does if not trying /:param. However, when trying /:param you can see that there is an extra /test/ in the path before /App.
Please someone help, as I would like to consume the parameter in the controller once it is correct.
You URL for this route should be like this : http://localhost:3880/test/app Where app is param.
Use absolute path for templateUrl. relative url wont work.
templateUrl: "/path/to/App/Test.html",

Categories

Resources