How use swagger generated "javascript-closure-angular-client" with AngularJS project - javascript

I'm newb to swagger , I have generated javascript-closure-angular-client from swagger-editor.
I want to used javascript-closure-angular-client in my AnuglarJS project. But I can't find any explanation for how to use it with AnuglarJS project.
Can anyone guide me for how to used javascript-closure-angular-client with AnuglarJS project?

I recommend you use swagger-js-codegen
Repository: https://github.com/wcandillon/swagger-js-codegen
And in this repository I explain how to generate the client in this case called clientAngularSwagger.js:
https://github.com/CayetanoHerreraLuisRicardo/swagger-angularjs-client
The next step would be:
To add it to your AngularJS project, do the following:
Add the generated file in the project for example:
<script src="js/models/clientAngularSwagger.js" type="text/javascript"></script>
Inject factory to controller
angular.module('App').controller('test', function ($scope, clientSwagger) {
....
}
and finally do requests to the web service in test controller
//clienSwagger object
$scope.swaggerObject = new clientSwagger("APIurl",false); //the parameter "APIurl" is optional, because in the clientSwagger factory is defined
//paramether to send
$scope.parameters = [];
$scope.parameters["authorization"]="Bearer xxxxxxxx";
$scope.parameters["xparameter"]="xxxx";
$scope.data = [];
//request function http
$scope.BBBObject.herefunctionname($scope.parameters).then(function(res)
{
$scope.data= res.data;
}, function(e) {
console.log(e);
});

Related

Connect external API to angular js

I have this external API on the global scope:
var _viewerApi = function(){
var selectedObject = null;
return {
selectObject: function(obj){
selectedObject = obj;
},
getSelectedObject: function(){
return selectedObject;
}
}
}
viewerApi = _viewerApi();
I have another external non-angular package talking with this api.
How do I attach this so angular checks the getSelectedObject? I want to fire angular events when getSelectedObject returns something
I guess I need to do a service and connect this somehow?
You can save the above code in a separate file. Export that file into the relevant js file where you want to use the service. Inject that service into the angular controller you want to use within. It will create a instance of service to be used within a controller.

AngularJS Module Injection logic understand

Im learning AngularJS and his separation of concerns using module.
I have created a simple app that is composed by an index.html that is the view, and two file .js, one for the controller and one for my own service.
The question is the following: How i can inject the .js file that contains the service, into the one for the controller?
That's my controller.js
var myApp = angular.module('myApp',[]);
myApp.controller('myController', function($scope, $window,$interval,$location) {
$scope.appUrl = $location.absUrl();
$scope.port = $location.port();
$scope.protocol = $location.protocol();
$scope.winWidth = $window.innerWidth;
$interval(function(){
$scope.winWidth = $window.innerWidth;
}, 1);
});
and this is the date-time-service.js
var service = angular.module('myApp',[]);
service.factory('dateTimeService', function() {
var dateTimeSvc = {};
dateTimeSvc.getData = function(){
return new Date().toDateString();
}
dateTimeSvc.getTime = function(){
return new Date().toTImeString();
}
return dateTimeSvc;
})
Obviosly i know that i can create a single .js file that contains both and call it into my view, but i want to understand the logic behind the dependencies injection starting with this "stupid" application, and then extends it to a little bit larger applications.
Thanks you all anticipately for all the answers!
We don't inject the js file. We inject dependencies.
If you are looking into how to dynamically inject modules in run time after angular context is initialisized -- its here http://blog.getelementsbyidea.com/load-a-module-on-demand-with-angularjs/
I have implemented this long ago where I dynamically call modules from server and inject it into my angular context based on which screen the user is in.

Share Service Between Two Different Modules and two different js files

I have checked many questions but no one clearly give examples which uses different js files.
I am working on angular js, and I'm stuck in the following issue.
Issue is, I want to Call functions which is in different js file and has different modules.
Now I Create "Service",which handles both modules and both functions,here is my Code,
First Module in first.js
var TaskAPP = angular.module('TaskApp', []);
TaskAPP.factory("TestService", function () {
var users = ["ad", "bf", "tt"];
return {
all: function () {
return users;
},
first: function () {
return users[0];
}
};
});
second module in second.js
var LabAPP = angular.module('LabApp', ['TaskApp', 'TestService']);
LabAPP.controller("LabController", function ($scope, TestService) {
$scope.aa = TestService.first();
});
but here on this page,error occur Error: $injector:modulerr
Module Error
Can any one help?
Your TestService is defined on TaskAPP, which is why it can't be used in LabApp. The solution is to create a module just for services, you want shared across modules.
For example, create a module just to hold shareable services:
angular.module('SharedServices', [])
.service('TestService', function(){
// code
}
Then inject SharedServices module into whichever module you want to access the service from:
angular.module('TaskAPP', ['SharedServices'])
Then access the service you want using SharedServices.TestService.fooMethod()
Your mistake is to use the service name TestService as a module dependency - this line:
var LabAPP = angular.module('LabApp', ['TaskApp', 'TestService']);
This fails, because there is no module called TestService, there is only a service inside the module TaskApp with that name. This should work:
var LabAPP = angular.module('LabApp', ['TaskApp']);
LabAPP.controller("LabController", function ($scope, TestService) {
$scope.aa = TestService.first();
});
Love from Switzerland :)

Cant unit test application with manual bootstrap in AngularJS

my code needs to do manual bootstrap cause requires loading files before laoding application.
var bootstrapModule = angular.module('bootstrapModule', []);
// the bootstrapper service loads the config and bootstraps the specified app
bootstrapModule.factory('bootstrapper', function ($http, $log, $q, $timeout) {
return {
bootstrap: function (appName) {
var deferred = $q.defer();
$http.get('config/urls/development.json')
.success(function (data) {
.....
deferred.resolve();
})
.error(function (data) {
...
});
return deferred.promise;
}
};
});
// create a div which is used as the root of the bootstrap app
var appContainer = document.createElement('div');
// in run() function you can now use the bootstrapper service and shutdown the bootstrapping app after initialization of your actual app
bootstrapModule.run(function (bootstrapper) {
bootstrapper.bootstrap('angular3App').then(function () {
// removing the container will destroy the bootstrap app
if (appContainer) appContainer.remove();
});
});
// make sure the DOM is fully loaded before bootstrapping
angular.element(document).ready(function () {
angular.bootstrap(appContainer, ['bootstrapModule']);
});
I want my unit tests to replicate this behaviour so it can have the info in the loaded file.
I am trying to bootstrap my app in beforeEach but it is not working.
beforeEach(function(done) {
var bootstrapModule = module('bootstrapModule')
// create a div which is used as the root of the bootstrap app
var appContainer = document.createElement('div');
// in run() function you can now use the bootstrapper service and shutdown the bootstrapping app after initialization of your actual app
bootstrapModule.run(function (bootstrapper) {
bootstrapper.bootstrap('angular3App').then(function () {
// removing the container will destroy the bootstrap app
appContainer.remove();
});
});
// make sure the DOM is fully loaded before bootstrapping
angular.element(document).ready(function () {
angular.bootstrap(appContainer, ['bootstrapModule']);
});
});
It is not bootstrapping accordingly. The information in my scope that is dependent from load of the bootstrapped loaded file is not available.
Anyone has any ideas?
This is an old question, but I just dealt with this issue and it seems that at least one other person has recently had a similar issue. I was banging my head against the wall to get my unit tests to run with a setup my like #saulovenancio. The factory was a way I found to import the config.json file needed for the project and it worked - it just didn't play nice with our tests.
As far as I could tell, the tests were trying to run before the promise in the bootstrapMOodule.factory was resolved. Luckily, while loading the config JSON was a requirement - loading it via service was not a project requirement - so I scrapped the service that was fetching the JSON.
I pretty much followed the approach outlined here:
How to configure your AngularJS application using environment variables
In the index.html document I added a script tag for an env.js file before the file that loads my angular app.
<html>
...
<script src="js/jquery.js"></script>
<!-- Gets the config.json -->
<script src="env.js"></script>
<!-- The App -->
<script src="js/main.js"></script>
</html>
The env.js file contains the code that loads the config.json onto the window. Mine looks something like this:
(function (window) {
window.__env = window.__env || {};
$.get( 'config.json', function( data ){
window.__env = data;
})
.error( function handleErrorResponse( xhr, status, error ){
console.error( "An AJAX error occured: " + status + "\nError: " + error ) ;
});
}(this));
From here I just loaded the window.__env into my main.js file and used it for my constants.
var env = {};
if(window){
Object.assign(env, window.__env);
}
...
angular.module('app').constant('AppSettings', env);
Once I made those changes everything worked like a charm ... big thanks to Jurgen Van de Moere. Hopefully, this will be helpful to someone.

AngularJs Protractor: Using ngMockE2E with a manually bootstrapped application

I am trying to mock data being responded to from an angularjs service using Protractor. I have been able to successfully do this in other applications by using the following technique.
Creating a mock module that is configurable via protractor.addMockModule
var httpBackendMock = function() {
angular.module('mockBackend', ['ngMockE2E', 'MyApp'])
.value('configData', arguments[0])
.run(function($httpBackend,configData) {
console.log('bootstrapped!');
$httpBackend.whenPOST(/.*/).respond(configData.postHeader, configData.postResponse);
});
};
module.exports.httpBackendMock = httpBackendMock;
Then creating a protractor test that looks like this
describe('Mocking an httpbackend', function() {
var sampleData = require('./sampleData/blog/normalLanding.json');
var configObject = require('./utils/backendConfig.json');//passed To addMockModule to be accessed via arguments[0]
var MyMockedBackend = require('./utils/httpBackendMock.js');
var ptor = protractor.getInstance();
configObject.postHeader = 200;
configObject.postResponse = sampleData;
it('Should mock a backnd', function(){
ptor.addMockModule('mockBackend', MyMockBackend.httpBackendMock, configObject);
ptor.get('/blog');
});
});
This worked perfectly for an app that was
The only angular application running on the page
Was bootstrapped via ng-app
However when working with an app that is manually bootstrapped, the app calls and returns the results from the actual service, rather than the desired mocked response. Also, no errors are thrown. For example's sake, I am trying to respond to all POST requests with the same data.
I have protractors rootElement in my configuration file set to the tag the app bootstraps on.
Does anything look particulary wrong with this settup/approach? Or could it be an issue with the order in which protractor executes in relation to calling addMockModule with a manually bootstrapped application?
Here is a link to a github repo which contains a working example of this with the Angular Phonecat Tutorial from the Angular website. The examples are in test/e2e/utils and scenerios.js
Github example
Cheers!

Categories

Resources