Can't get factory or service to be recognized in controller with angluarjs using angular-seed - service

I keep getting "undefined is not a function" when calling the factory. I am using the angular-seed as the framework for my setup. For some reason, it doesn't recognize "GetFormVals" as a valid factory.
In app.js:
var app = angular.module('myApp', ['myApp.filters',
'myApp.services', 'myApp.directives'], function($routeProvider, $locationProvider) {
//route declarations
$routeProvider.when('/fsr', {
templateUrl: 'partials/fsr.html',
controller: ctrlFSR
});
$locationProvider.html5Mode(true);
});
In controllers.js:
function ctrlFSR($scope, $http, $location, GetFormVals) {
$scope.test = GetFormVals();
}
ctrlFSR.$inject = ['$scope','$location'];
In services.js:
'use strict';
/* Services */
angular.module('myApp.services', []).
factory('GetFormVals', function(){
return "test";
});
I have to be missing something simple.
jsfiddle: http://jsfiddle.net/wUjw5/11/

You need to list all the dependencies to be injected into your controller:
function ctrlFSR($scope, $http, $location, GetFormVals) {
$scope.test = GetFormVals();
}
ctrlFSR.$inject = ['$scope', '$http', '$location', 'GetFormVals'];

Change your service to this
'use strict';
/* Services */
angular.module('myApp.services', []).
factory('GetFormVals', function(){
return {
exampleValue: "test5"
}
});
Then in your controller you would update it to this:
function ctrlFSR($scope, $http, $location, GetFormVals) {
$scope.test = GetFormVals.exampleValue;
}
ctrlFSR.$inject = ['$scope','$location'];
I think the confusion came in with you calling GetFormVals as a function, while in reality it's a service.
jsfiddle: http://jsfiddle.net/rtCP3/49/
your js fiddle modified http://jsfiddle.net/wUjw5/12/
Don't inject with ctrlFSR.$inject = ['$scope','$location'];. You already are.

Related

how to use third party javascript code in magento2 payment?

I am facing problem while adding third party javascript code in my payment module in magento2.
following is my code.
define(
[
'Magento_Payment/js/view/payment/cc-form',
'jquery',
'Vendorname_Modulename/js/stsdk'
'Magento_Payment/js/model/credit-card-validation/validator'
],
function (Component, $, STDirect) {
'use strict';
return Component.extend({
defaults: {
template: 'Vendorname_Modulename/payment/module-form'
},
getCode: function() {
return 'vendor_module';
},
isActive: function() {
return true;
},
validate: function() {
STDirect.setupSDK('23842', "testnumber", 'typeofenv');
STDirect.card.createToken(number, exp_month, exp_year, ccv, function (result) {
var secretkey = '';
if(result.status==0){
secretkey = result.card.secretkey;
}
document.write(JSON.stringify(result));
alert(secretkey);
});
var $form = $('#' + this.getCode() + '-form');
return $form.validation() && $form.validation('isValid');
}
});
}
);
I have tried above code, stsdk.js is loaded in network but it gives me following error :
ReferenceError: STDirect is not defined
STDirect.setupSDK('23842', "testnumber", 'sandbox');
I have also checked by load this js file in header but same error appear.
My question is how to execute third party javascript code in define scope.
I tried with the custom javascript function after define function but it is also not callable from validate function and when I use require[] function within define function it raise error.
I appreciate any help.

Session::flash is not working in Laravel version 5.2.27

I am trying to display a success message upon form submit in Laravel.
However, it doesn't work.
I've added use Session; at the top of the controller file, the routes are in the middleware and the configuration in config/session.php is the default one.
My controller function is able to save in the database without any problem :
public function store(Request $request)
{
$post = new Post;
$post->title = $request->title;
$post->description = $request->description;
$post->slug = $request->slug;
$post->body = $request->body;
$post->save();
Session::flash('success', 'SUCCESS MESSAGE GOES HERE');
return redirect()->route('posts.show', $post->id);
}
here is my template file :
#if(Session::has('success'))
<div class="alert-box success">
<h2>{{ Session::get('success') }}</h2>
</div>
#endif
My routes :
Route::group(['middleware' => ['web']], function() {
Route::get('/', 'PagesController#getIndex');
Route::resource('posts','PostController');
});
Is see there is no success in the session file. I cannot figure out why exactly :
a:4:{s:6:"_token";s:40:"EntXIr9tkqAcKarDZhaNxKb6RfcFdFV9ZtF6W7kU";s:9:"_previous";a:1:{s:3:"url";s:30:"http://localhost:8000/posts/35";}s:5:"flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}s:9:"_sf2_meta";a:3:{s:1:"u";i:1459467699;s:1:"c";i:1459467699;s:1:"l";s:1:"0";}}
Someone can help me figure out what the problem is?
The web middleware no longer needs to be explicitly applied to routes in your routes.php file. It is now silently applied to routes within app/Providers/RouteServiceProvider.php, as per this change in Laravel 5.2.27
Previously you would be required to explicitly apply the web middleware to routes like so:
Route::group(['middleware' => ['web']], function () {
Route::get('/', function () {
return view('welcome');
});
});
The above can now be achieved like so:
Route::get('/', function () {
return view('welcome');
});
Make sure the route is using the "web" middleware to access session data.
Route::group(['middleware' => 'web'], function () {
Route::get('foo', 'FooController#bar'); // session data should be available here
});

Custom authorizer not called

I'm trying to implement a custom authorizer (using ember-cli and ember-cli-simple-auth) but the authorize method is not being called on any requests. The init function is being called and the message that appears in the console when there is no authorizer registered is no longer showing up. Here is the initializer code:
import Ember from 'ember';
import Base from 'simple-auth/authorizers/base';
import ENV from '../config/environment';
ENV['simple-auth'] = ENV['simple-auth'] || {};
ENV['simple-auth'].authorizer = 'authorizer:custom';
ENV['simple-auth'].crossOriginWhiteList = [ENV.NET.API_ENDPOINT];
var CustomAuthorizer = Base.extend({
init: function () {
console.log('Intialize authorizer');
},
authorize: function(jqXHR, requestOptions) {
console.log('Authorize');
var token = this.get('session.token');
if(this.get('session.isAuthenticated') && !Ember.isEmpty(token)) {
authValue = "Token " + token;
jqXHR.setRequestHeader('Authorization', authValue);
}
}
});
export default {
name: 'authorization',
before: 'simple-auth',
initialize: function(container, application) {
console.log('Registered');
container.register('authorizer:custom', CustomAuthorizer);
}
};
Any help would be appreciated.
Problem here was something quite dumb: my casing of crossOriginWhitelist was incorrect.

How to serve 404's using AngularJS and a RESTful API

Let's say you have an AngularJS application hooked up to a RESTful API and you have a route for "/item/:itemId".
.when('/item/:itemId', {
templateUrl: '/static/partials/item-detail.html',
controller: ItemDetailController
})
angular.module('angServices', ['ngResource']).factory('Item', function($resource) {
return $resource('/api/item/:itemId', {}, {
query: { method: 'GET', params: { itemId: '' }, isArray: true }
});
});
If the user goes to "/item/9" and an object with the itemId 9 does not exist, Angular will receive a 404 from the API, but will not naturally return a 404 to the user.
In other questions, I've seen people suggest creating an interceptor and having Angular redirect to a 404 error page when a resource is not found.
var interceptor = ['$rootScope', '$q', function(scope, $q) {
...
function error(response) {
if (response.status == 404) { window.location = '/404'; }
...
$httpProvider.responseInterceptors.push(interceptor);
However, I want to return a correct 404 with the original requested URL for SEO purposes.
Also, the solution above first loads the page and then redirects (just like Twitter used to do), so its sub-optimal.
Should I check server-side to first see if the resource exists before passing the request on to the Angular app? The downside of this is that it wouldn't work for broken links within the application.
What is the best way to approach this?
Maybe this jsfiddle can help you.
http://jsfiddle.net/roadprophet/VwS2t/
angular.module('dgService', ['ngResource']).factory("DriveGroup", function ($resource) {
return $resource(
'/', {}, {
update: {
method: 'PUT'
},
fetch: {
method: 'GET',
// This is what I tried.
interceptor: {
response: function (data) {
console.log('response in interceptor', data);
},
responseError: function (data) {
console.log('error in interceptor', data);
}
},
isArray: false
}
}
);
});
var app = angular.module('myApp', ['ngResource', 'dgService']);
app.controller('MainController', ['$scope', 'DriveGroup', function ($scope, svc) {
$scope.title = 'Interceptors Test';
svc.fetch(function (data) {
console.log('SUCCESS');
}, function () {
console.log('FAILURE');
});
}]);
I tried with this and works fine. I only change the fetch method to get.
In your case, you will need to change the console.log('FALIURE'); to $location.path('/404');.
GL!

Testing Angular $resource with external service

I'm trying to make some basic tests on REST requests I'm doing using Angular $resource.
The service code works just fine.
'use strict';
angular.module('lelylan.services', ['ngResource']).
factory('Device', ['Settings', '$resource', '$http', function(Settings, $resource, $http) {
var token = 'df39d56eaa83cf94ef546cebdfb31241327e62f8712ddc4fad0297e8de746f62';
$http.defaults.headers.common["Authorization"] = 'Bearer ' + token;
var resource = $resource(
'http://localhost:port/devices/:id',
{ port: ':3001', id: '#id' },
{ update: { method: 'PUT' } }
);
return resource;
}]);
I'm using the Device resource inside a directive and it works. The problems comes out
when I start making some tests on the services. Here is a sample test where I mock the
HTTP request using $httpBackend and I make a request to the mocked URL.
Unluckily it does not return anything, although the request is made. I'm sure about this
because if a request to another URL is made, the test suite automatically raises an error.
I've been spending lot of time, but no solutions. Here the test code.
'use strict';
var $httpBackend;
describe('Services', function() {
beforeEach(module('lelylan'));
beforeEach(inject(function($injector) {
var uri = 'http://localhost:3001/devices/50c61ff1d033a9b610000001';
var device = { name: 'Light', updated_at: '2012-12-20T18:40:19Z' };
$httpBackend = $injector.get('$httpBackend');
$httpBackend.whenGET(uri).respond(device)
}));
describe('Device#get', function() {
it('returns a JSON', inject(function(Device) {
device = Device.get({ id: '50c61ff1d033a9b610000001' });
expect(device.name).toEqual('Light');
}));
});
});
As the device is not loaded this is the error.
Expected undefined to equal 'Light'.
Error: Expected undefined to equal 'Light'.
I've tried also using the following solution, but it doesn't get into the function
to check the expectation.
it('returns a JSON', inject(function(Device) {
device = Device.get({ id: '50c61ff1d033a9b610000001' }, function() {
expect(device.name).toEqual('Light');
});
}));
Any suggestion or link to solve this problem is really appreciated.
Thanks a lot.
You were very close, the only thing missing was a call to the $httpBackend.flush();. The working test looks like follows:
it('returns a JSON', inject(function(Device) {
var device = Device.get({ id: '50c61ff1d033a9b610000001' });
$httpBackend.flush();
expect(device.name).toEqual('Light');
}));
and a live test in plunker: http://plnkr.co/edit/Pp0LbLHs0Qxlgqkl948l?p=preview
You might also want to check docs for the $httpBackend mock.
In later versions of angular, I'm using 1.2.0rc1 you also need to call this within a $apply or call $digest on a scope. The resource call isn't made unless you do something like this:
var o, back, scope;
beforeEach(inject(function( $httpBackend, TestAPI,$rootScope) {
o = TestAPI;
back = $httpBackend;
scope = $rootScope.$new();
}));
it('should call the test api service', function() {
back.whenGET('/api/test').respond({});
back.expectGET('/api/test');
scope.$apply( o.test());
back.flush();
});