Is there anything wrong with this code where I am trying to have one service method point to different restful services?
var phonecatServices = angular.module('phonecatServices', ['ngResource']);
phonecatServices.factory('Phone', ['$resource',
function ($resource) {
return {
pList: $resource('/:url/:phoneId.json.htm', {}, {
query: { method: 'GET', params: { url: 'MyAngularScripts', phoneId: 'jsonPhonedata' }, isArray: true }
}),
pDetail: $resource('/Content/PhonesData/:phoneId.json.htm', {}, {
query: { method: 'GET', params: { phoneId: $routeParams.phoneId }, isArray: false }
})
};
}]);
Then in my controller I call the pList like this:
$scope.phones = Phone.pList.query();
The service method doesnt get called with any of the code above. However if I change the service to this:
var phonecatServices = angular.module('phonecatServices', ['ngResource']);
phonecatServices.factory('Phone', ['$resource',
function ($resource) {
return $resource('/:url/:phoneId.json.htm', {}, {
query: { method: 'GET', params: { url: 'MyAngularScripts', phoneId: 'jsonPhonedata' }, isArray: true }
});
}]);
and call from the controller like this:
$scope.phones = Phone.query();
IT works. What is wrong with the service where I have multiple restful calls declared? SOmething wrong with the way its configured or the way I am calling it?
The 1st approach should be working fine as well.
The only oroblem is that you are trying to access a property of $routeParams, without first injecting it via DI, thus resulting in an Error being thrown.
If you correct this, everything should work as expected.
Related
I am working with Angular2 and es5. I want to use http in a service.
Unfortunately I have 2 errors:
- http is undefined, but ng.http.Http is defined,
- I have this error for the main component:
vendor-client.min.js:28 EXCEPTION: Can't resolve all parameters for class0: (t, ?)
Here is my service code:
;(function(app, ng) {
console.log(new ng.http.Http());
app.ApplicationsService = ng.core.Injectable().Class({
constructor: [ng.http.Http, function(http) {
console.log(http);
this.applicationsEmailUrl = 'api/applications/email';
this.http = http;
}],
emailExists: function(email) {
console.log(email);
var data = { email: email };
return this.http.post(this.applicationsEmailUrl, data)
.toPromise()
.then(function(response) { response.json().data; })
.catch(this.handleError);
}
});
})(window.app || (window.app = {}), window.ng);
Here is the main component:
;(function(app, ng) {
app.AppComponent = ng.core
.Component({
selector: 'register-form',
templateUrl: 'src/register/app.component.html'
})
.Class({
constructor: [ng.core.ElementRef, app.ApplicationsService, function(ref, Applications) {
console.log('app.component.js');
this.programs = JSON.parse(ref.nativeElement.getAttribute('programs'));
this.applications = Applications;
}],
emailExists: function(email) {
console.log('emailExists() triggered');
Applications.emailExists(email);
}
});
})(window.app || (window.app = {}), window.ng);
The bootstrap:
;(function(app, ng) {
document.addEventListener('DOMContentLoaded', function() {
ng.platformBrowserDynamic.bootstrap(app.AppComponent, [
ng.forms.disableDeprecatedForms(),
ng.forms.provideForms(),
ng.http.HTTP_PROVIDERS,
app.ApplicationsService
]);
});
})(window.app || (window.app = {}), window.ng);
If I try to inject http into the main component within the providers array, it works. But I would rather prefer to have a service.
I found out the problem. Looks like Angular2 needs to load your code in order. The main component was loaded before the service, so it was undefined. I put all my code in one file and it works. I will use a require loader asap.
I'm new to Angualrjs and I'm trying to figure out this code... this is how the service looks like
var userGroupServices = angular.module('userGroupServices', ['ngResource']);
userGroupServices.factory('UserRoles', ['$resource', function ($resource) {
var r1 = $resource('/api/UserRoles/:UserRoleId', null, {
'update': { method: 'PUT' },
'delete': { method: 'DELETE' }
});
r2 = $resource('/api/UserRoles', null, {
'add': { method: 'POST' },
'getRoles': { method: 'GET' }
});
r3 = $resource('/api/UserRoles/GetRolesByGroupType/:groupTypeName', null, {
'getRolesByName': {method:'GET'}
});
r1.getAll = r2.getRoles.bind(r2);
r1.add = r2.add.bind(r2);
r1.getRolesByName = r3.getRolesByName.bind(r3);
return r1;
}]);
Why is it in the end, you bind r2 and r3 variables into r1 variable? how do i use this factory to POST something, i try to post it like this way but it didn't do anything(in my controller)...
addService.addRole({ roleName: groupTypeName });
I think the reason why resources 2 and 3 are being combined and returned by resource 1 is to abstract these other resources away from someone who wants to use the UserRoles service. Now you don't need to know about how many resources the service needs in order to work.
As for posting, .addRole() doesn't seem to exist in your service. Try UserRoles.add({object}).
Senario is:
mcalendar: model,
mevent: model,
relationship: mcalendar has_many mevents,
in the mcalendar.show route I have:
model: function(params) {
return this.store.find('mcalendar', params.mcalendar_id);
},
what I want to do is:
to have a function in the mcalendar.show route to return all mevents of mcalendar in the form of an array. Something like this:
A HOOK(maybe afterModel): function(){
//return all mevents like:
return {
events: Ember.A([
{
title: mevent.get('title'),
start: mevent.get('start')
}])
the purpose is to use this array for feeding fullCalendar. I have tried some ways but none of them was successful.
Ember cli: 0.2.7
Thanks
are your mevents returned in the payload when requesting mcalendar? if so, you could do this in the setupController hook instead like...
setupController: function(controller, model) {
controller.set('events', model.get('mevents').toArray());
}
afterModel: function () {
var _this = this;
var model = this.modelFor(this.routeName);
return model.get('mevents').then(function(mevents) {
var allMevents = mevents.map(function(mevent){
return {
title: mevent.get('title'),
start: mevent.get('start')
};
});
_this.controllerFor('mcalendars.show').set('events', allMevents);
});
},
I have a Meteor application with a publish of:
Meteor.publish('my_items', function() {
var selector = {owner_id: this.userId};
var items = ItemOwnership.find(selector, {fields: {item_id: 1}}).fetch();
var itemIds = _.pluck(items, 'item_id');
return Items.find({
_id: {$in: itemIds},
item_archived_ts: { $exists: false }
});
});
and a subscription of this:
Meteor.subscribe('my_items');
The application allows for the user to add items to the 'Items' collection and this is done by calling a server method. The Items collection on the server is updated with the new record, but the client-side equivalent collection is not showing the new record. Is there anything obviously wrong with what I am doing, or some way to debug this?
p.s. there are no client/server-side errors occurring?
I found a way to accomplish this using the reywood:publish-composite Meteor package. Here is the publish that achieves this:
Meteor.publishComposite('my_items', {
find: function () {
var selector = {owner_id: this.userId};
return ItemOwnership.find(selector, {fields: {item_id: 1}});
},
children: [
{
find: function(IOrecord){
return Items.find({
_id: IOrecord.item_id,
item_archived_ts: { $exists: false }
});
}
}
]
});
I have a route I call many times. I have to subscribe two collections for having all datas, here's a snapshot:
var one = new Blaze.ReactiveVar(false);
var two = new Blaze.ReactiveVar(false);
this.route('stopIndex', {
path: '/stop/:section/:stop_id',
waitOn: function() {
Meteor.call('getTripIdsForStop', {
stop_id: this.params.stop_id,
from: fromNow(),
to: toMax(),
db: prefix
}, function(err, ids) {
DEBUG && console.log('TRIP_IDS:', ids);
Meteor.subscribe(prefix + '_trips', {
trip_id: {$in: ids}
}, function() {
one.set(true);
});
Meteor.subscribe(prefix + '_stop_times', {
trip_id: {$in: ids}
}, function() {
two.set(true);
});
});
return [
function () { return one.get(); },
function () { return two.get(); }
];
},
The first time I call the route, all goes fine. The second time, the one and two vars are already setted to true so the waitOn doesn't wait and I get a no data message on my template for some seconds, until collections responds. I've tried putting on the first lines of waitOk method:
one.set(false);
two.set(false);
but this makes the waitOn to wait forever. Am I doing something wrong or missing something? Thanks for the help.
I've solved this way:
Router.onStop(function() {
one.set(false);
two.set(false);
});
that invalidates ReactiveVars and will wait. I've also moved all code from waitOn to data. Now the waitOn is like this:
return [
function () { return one.get(); },
function () { return two.get(); }
];