Angular ui-router resolve, http success, stateParams - php

My goal to achieve is:
first to insert new database record with http post, resolve with stateProvider and grab the new id and change view and stateParams.
i have this code for my http post service
myApp.service('postService', ['$http', function($http) {
this.insertNew = function() {
$http.post('create_new.php')
.success(function(data) {
return data;
});
};
create_new.php returns the ID like this (it works, proved with console)
return json_encode($data);
and the stateProvider looks like this (section)
$stateProvider
.state('newRecord', {
resolve: {
newArtID: ['postService',
function(postService) {
return postService.insertNew();
}]
},
params: {
artID: <-- new ID from DB
},
i did tests with stateParams in serval variations (in resolve and by params). how can i bring the new ID to stateParams, so i can access from the views?
Thanks for any help!

I'm not so sure your oder of operations is correct. params is for when you already have that data. You should return the data from your resolve, then you can access it in your scope, for ex:
Service:
.service('postService', function ($http) {
this.insertNew = function () {
return $http.post('create_new.php').then(function (data) {
return data;
});
}
})
Route:
$stateProvider
.state('newRecord', {
views: {
"main": {
controller: 'SomeCtrl',
templateUrl: '...'
}
},
resolvedId: {
newArtID: function (postService) {
return postService.insertNew().then(function (response) {
return response;
});
}
}
})
Controller:
.controller('SomeCtrl', function (resolvedId) {
var newID = resolvedId.id; //depending on what is returned
});

Related

Vue data does not display value on console but does display on component

I'm trying to retrieve a global session value and set it to the vue variable. The problem is, the id variable is not displaying any value on the console but does display the value on the vue component. I've checked with the vue devtools and the id does contain the correct value.
Vue Component
<template>
<div class="container">
<h1>{{id}}</h1> // the id does displays the value
</div>
</template>
<script>
export default {
data () {
return {
id:'',
}
},
created(){
axios.get('api/studentlecture').then(response => this.id = response.data).catch(function(error){console.log(error)
});
console.log(this.id)
},
methods:{
},
mounted() {
console.log('Component mounted.')
}
}
Controller
public function index()
{
$id= session('userID');
return json_encode($id);
}
Because the axios call is asynchronous. The JavaScript engine will execute the axios request, and while it is waiting it will continue executing the code.
You are trying to log this.id while it has not yet been assigned. If you want to log the value, you have to put it in the callback of your axios function.
axios.get('api/studentlecture')
.then(response => {
this.id = response.data;
console.log(this.id); // <== Here
})
.catch(function(error){console.log(error)});
This happens because console.log(this.id) is executed before axios.get() could resolve it's promise.
There are a few solution for this.
First one is to move console.log() inside then().
created() {
axios.get('api/studentlecture').then(response => {
this.id = response.data;
console.log(this.id);
}).catch(error => {
console.log(error)
});
}
Or you can make use of async/await to wait the promise to resolve
async created() {
try {
// This will wait until promise resolve
const response = await axios.get('api/studentlecture');
this.id = response.data;
console.log(this.id);
} catch(error) {
console.log(error)
}
}
You can learn more about promise here
And more about async/await difference with promise here
You can try using the following code below:
/*FRONT-END VUE*/
this.axios.get("https://localhost:8000/api/v1/data").then((response)=>{
this.data=response.data;
console.log(this.data);
if(this.data.success){
}
});
/*BACK-END LARAVEL*/
function getData(){
$result = array('success'=>true,'data'=>$data);
return Response()->json($result);
}

store php response in angularjs service, then get them in controller

So, I am new to angularjs. I want to use MVC structure. So, I was thinking that storing the response from php in my service, then use them in my controller.
Service:
(function () {
angular.module('dataService').service("incidentService", function ($http) {
var Data = [];
return ({
getData: __getData
});
function __getData() {
return Data;
}
function __setData($http, $q) {
var defer = $q.defer();
$http.get('PHP/NAME.php',{cache : 'true'}).
success(function(data){
Data = data;
console.log(Data);
defer.resolve(data);
defer.promise.then(function(data){
Data = data;
console.log(Data);
});
});
}
})})();
Controller:
(function () {
angular.module('app')
.controller('Ctrl', Ctrl);
/** #ngInject */
function Ctrl($scope, $http, $q,baConfig, incidentService) {
incidentService.setData($http,$q)
var DataSet = incidentService.getData();
console.log(DataSet);
}
})();
By doing this way, the problem is my dataSet does not get updated when the data array in my service is updated. I know that we can return a defer promise to controller to get the data, but can we set the data first in service, then use get method to use them?
OK, I think the biggest issue with why this doesn't work is because you're assigned the data returned by the $http call to nData rather than just Data.
The next issue is that there's not a getMonthlyData method defined on the service.
That being said, this looks overly complicated.
Your service should look more like this:
(function () {
angular.module('dataService').service("incidentService", function ($http,$q) {
var service
service.getData = __getData()
return service
function __getData() {
if (!service.Data) {
return $http.get('PHP/NAME.php',{cache : 'true'}).then( function(data) {
service.Data = data
return $q.when(service.Data)
})}
else {
return $q.when(service.Data)
}
}
})})();
Then in your controller you just get the data via incidentService.getData()

Angularjs How to get Parsed Data of Json Format return by the $http response in Service

First of all i want to clear, That am not accessing the data using web service.
My database(php) and angularjs UI are on the same server it self.
In Service of AngularJs, am sending http Get Request to interface.php(Database) it return json format. I dont how to actually parse the data and send it to Controller ?
Here Clear Cut Code :)
var app=angular.module("app.chart.ctrls",['ngSanitize']);
Controller
app.controller("registrationCtrl",["$scope","$location","logger","registerService",function($scope,$location,logger,registerService){
$scope.data= registerService.getYears();
**how to parse the data is it correct format or not ? in Controller**
}
**Service**
app.factory('registerService', function ($http,$q,$log) {
return {
getYears:function () {
var deferred = $q.defer();
$http({
method : "GET",
url : "interface.php",
}).success(function(data){
**** How to Return the data from here to Controller ***
})
},
}
});
interface.php
1 - First define a object in your controller that later you can use as a storage for your http response like this :
app.controller("registrationCtrl",["$scope","$location","logger","registerService",function($scope,$location,logger,registerService){
$scope.data = {};
// fire your servise function like this :
registerService.getYears($scope);
}
2- In your Servise :
app.factory('registerService', function ($http) {
return {
getYears:function (scope) {// scopes comes from your controller
$http({method : "GET",url : "interface.php"})
.success(function(data){
scope.data = data;!!!!!!
})
}
}
});
It's done so far and it'll work ;
BUT if your want to use some kind of promise , you can do like this :
in your controller :
.
.
.
$scope.data = {};
// fire your servise function like this :
var promise = registerService.getYears();
promise.then(function(msg){
$scope.data = msg.data[0];
});
.
.
.
in your Service :
app.factory('registerService', function ($http) {
return {
getYears:function () {
var promise = $http({method : "GET",url : "interface.php"});
}
return promise ;
});
from https://docs.angularjs.org/tutorial/step_11
the source:
[
{
"age": 13,
"id": "motorola-defy-with-motoblur",
"name": "Motorola DEFY\u2122 with MOTOBLUR\u2122",
"snippet": "Are you ready for everything life throws your way?"
...
},
...
]
your service looks like:
phonecatServices.factory('Phone', ['$resource',
function($resource){
return $resource('phones/:phoneId.json', {}, {
query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
});
}]);
and your controller:
phonecatControllers.controller('PhoneListCtrl', ['$scope', 'Phone', function($scope, Phone) {
$scope.phones = Phone.query();
$scope.orderProp = 'age';
}]);
so, you call the service from within the controller and get the results back.

Backbone.js, Unable to understand what is "app.wineList.create(this.model)" in the "saveWine" method

I am unable to understand what is "app.wineList.create(this.model)" in the "saveWine" method. How it will work ? I am new to backbone.js, plz help me to understand this. I am aware of this.model.save().
Actually I have removed some code here. Just I have posted the code where my problem was.
Thanks.
// Models
window.Wine = Backbone.Model.extend({
urlRoot:"../api/wines",
defaults:{
"id":null,
"name":"",
"grapes":"",
"country":"USA",
"region":"California",
"year":"",
"description":"",
"picture":""
}
});
window.WineCollection = Backbone.Collection.extend({
model:Wine,
url:"../api/wines"
});
// Views
window.WineView = Backbone.View.extend({
template:_.template($('#tpl-wine-details').html()),
initialize:function () {
this.model.bind("change", this.render, this); // (event, function, context)
},
render:function (eventName) {
$(this.el).html(this.template(this.model.toJSON()));
return this;
},
events:{
"click .save":"saveWine"
},
saveWine:function () {
this.model.set({
name:$('#name').val(),
grapes:$('#grapes').val(),
country:$('#country').val(),
region:$('#region').val(),
year:$('#year').val(),
description:$('#description').val()
});
if (this.model.isNew()) {
app.wineList.create(this.model);
} else {
this.model.save();
}
return false;
}
});
// Router
var AppRouter = Backbone.Router.extend({
routes:{
"":"list",
"wines/:id":"wineDetails"
},
initialize:function () {
$('#header').html(new HeaderView().render().el);
},
list:function () {
this.wineList = new WineCollection();
this.wineListView = new WineListView({model:this.wineList});
this.wineList.fetch();
$('#sidebar').html(this.wineListView.render().el);
},
wineDetails:function (id) {
this.wine = this.wineList.get(id);
if (app.wineView) app.wineView.close();
this.wineView = new WineView({model:this.wine});
$('#content').html(this.wineView.render().el);
}
});
var app = new AppRouter();
Backbone.history.start();
As described in the Backbone documentation:
Convenience to create a new instance of a model within a collection.
Equivalent to instantiating a model with a hash of attributes, saving
the model to the server, and adding the model to the set after being
successfully created.
So it adds a model to your winelist collection, and saves it to server.

Backbone.js model.destroy() not sending DELETE request

I've been trying for days to get this working and I just cannot figure out why when I have my view to destroy a model which belongs to a collection (which properly has a url attribute for the beginning fetch of models' data), only fires the destroy 'event' which is bubbled up to the collection for easy binding by my list view. But it does not ever send an actual DELETE request or any request to the server at all. Everywhere I look, I see everyone using either the collection's url attr, or urlRoot if the model is not connected to a collection. I've even tested before the actual this.model.destroy() to check the model < console.log(this.model.url());
I have not overwritten the destroy nor sync methods for backbone. Also each model does have an id attribute which is populated via the collection's fetch (from database records).
The destroy takes place in the list item view, and the collection's "destroy" event is bound in the list view. All that works well (the event handling), but the problem, again, is there's no request to the server.
I was hoping that backbone.js would do it automatically. That was what the documentation implies, as well as the numerous examples everywhere.
Much thanks to anyone who can give some useful input.
FYI: I'm developing on wampserver PHP 5.3.4.
ListItemView = BaseView.extend({
tagName: "li",
className: "shipment",
initialize: function (options) {
_.bindAll(this);
this.template = listItemTemplate;
this.templateEmpty = listItemTemplateEmpty;
},
events: {
'click .itemTag' : 'toggleData',
'click select option' : 'chkShipper',
'click .update' : 'update',
'click button.delete' : 'removeItem'
},
// ....
removeItem: function() {
debug.log('remove model');
var id = this.model.id;
debug.log(this.model.url());
var options = {
success: function(model, response) {
debug.log('remove success');
//debug.log(model);
debug.log(response);
// this.unbind();
// this.remove();
},
error: function(model, response) {
debug.log('remove error');
debug.log(response);
}
};
this.model.destroy(options);
//model.trigger('destroy', this.model, this.model.collection, options);
}
});
Collection = Backbone.Collection.extend({
model: Model,
url: '?dispatch=get&src=shipments',
url_put : '?dispatch=set&src=shipments',
name: 'Shipments',
initialize: function () {
_.bindAll(this);
this.deferred = new $.Deferred();
/*
this.fetch({
success: this.fetchSuccess,
error: this.fetchError
});
*/
},
fetchSuccess: function (collection, response) {
collection.deferred.resolve();
debug.log(response);
},
fetchError: function (collection, response) {
collection.deferred.reject();
debug.log(response);
throw new Error(this.name + " fetch failed");
},
save: function() {
var that = this;
var proxy = _.extend( new Backbone.Model(),
{
url: this.url_put,
toJSON: function() {
return that.toJSON();
}
});
var newJSON = proxy.toJSON()
proxy.save(
newJSON,
{
success: that.saveSuccess,
error: that.saveError
}
);
},
saveSuccess: function(model, response) {
debug.log('Save successful');
},
saveError: function(model, response) {
var responseText = response.responseText;
throw new Error(this.name + " save failed");
},
updateModels: function(newData) {
//this.reset(newData);
}
});
ListView = BaseView.extend({
tagName: "ul",
className: "shipments adminList",
_viewPointers: {},
initialize: function() {
_.bindAll(this);
var that = this;
this.collection;
this.collection = new collections.ShipmentModel();
this.collection.bind("add", this.addOne);
this.collection.fetch({
success: this.collection.fetchSuccess,
error: this.collection.fetchError
});
this.collection.bind("change", this.save);
this.collection.bind("add", this.addOne);
//this.collection.bind("remove", this.removeModel);
this.collection.bind("destroy", this.removeModel);
this.collection.bind("reset", this.render);
this.collection.deferred.done(function() {
//that.render();
that.options.container.removeClass('hide');
});
debug.log('view pointers');
// debug.log(this._viewPointers['c31']);
// debug.log(this._viewPointers[0]);
},
events: {
},
save: function() {
debug.log('shipments changed');
//this.collection.save();
var that = this;
var proxy = _.extend( new Backbone.Model(),
{
url: that.collection.url_put,
toJSON: function() {
return that.collection.toJSON();
}
});
var newJSON = proxy.toJSON()
proxy.save(
newJSON,
{
success: that.saveSuccess,
error: that.saveError
}
);
},
saveSuccess: function(model, response) {
debug.log('Save successful');
},
saveError: function(model, response) {
var responseText = response.responseText;
throw new Error(this.name + " save failed");
},
addOne: function(model) {
debug.log('added one');
this.renderItem(model);
/*
var view = new SB.Views.TicketSummary({
model: model
});
this._viewPointers[model.cid] = view;
*/
},
removeModel: function(model, response) {
// debug.log(model);
// debug.log('shipment removed from collection');
// remove from server
debug.info('Removing view for ' + model.cid);
debug.info(this._viewPointers[model.cid]);
// this._viewPointers[model.cid].unbind();
// this._viewPointers[model.cid].remove();
debug.info('item removed');
//this.render();
},
add: function() {
var nullModel = new this.collection.model({
"poNum" : null,
"shipper" : null,
"proNum" : null,
"link" : null
});
// var tmpl = emptyItemTmpl;
// debug.log(tmpl);
// this.$el.prepend(tmpl);
this.collection.unshift(nullModel);
this.renderInputItem(nullModel);
},
render: function () {
this.$el.html('');
debug.log('list view render');
var i, len = this.collection.length;
for (i=0; i < len; i++) {
this.renderItem(this.collection.models[i]);
};
$(this.container).find(this.className).remove();
this.$el.prependTo(this.options.container);
return this;
},
renderItem: function (model) {
var item = new listItemView({
"model": model
});
// item.bind('removeItem', this.removeModel);
// this._viewPointers[model.cid] = item;
this._viewPointers[model.cid] = item;
debug.log(this._viewPointers[model.cid]);
item.render().$el.appendTo(this.$el);
},
renderInputItem: function(model) {
var item = new listItemView({
"model": model
});
item.renderEmpty().$el.prependTo(this.$el);
}
});
P.S... Again, there is code that is referenced from elsewhere. But please note: the collection does have a url attribute set. And it does work for the initial fetch as well as when there's a change event fired for saving changes made to the models. But the destroy event in the list-item view, while it does trigger the "destroy" event successfully, it doesn't send the 'DELETE' HTTP request.
Do your models have an ID? If not, the HTTP request won't be sent. –
nikoshr May 14 at 18:03
Thanks so much! Nikoshr's little comment was exactly what I needed. I spent the last 5 hours messing with this. I just had to add an id to the defaults in my model.

Categories