Angular js/Ionic access promise from a factory service - php

I am experiencing the same issue as posted in a recent topic - 30702965 Accessing objects returned from a factory. In fact I have followed the advice in that response but still do not get any results in the view. As in that previous post I have created a factory:
myapp.factory("eventsService", function($http) {
var events = [];
return {
getEvents: function() {
return $http.get('data/events.php').then(function(response) {
events = response;
// console.log(response);
return events;
});
}};
});
This returns the promise which is seen in the console.log.
I coded the controller as per the advice in the response as follows:
myapp.controller('eventsController', function($scope, eventsService) {
$scope.events = [];
eventsService.getEvents().then(function(data){
$scope.events = data;
console.log(data);
});
});
Again, the console.log shows that I have got the object:
object {data: Array[2], status: 200, config: Object, statusText: "OK"}
All good so far, but I still don't get anything in the view:
<ion-content ng-controller="eventsController">
<ion-item ng-repeat="event in events">{{ event.title }} </ion-item>
</ion-content>
I'm lost as how to display the events. What am I missing?
Oh, by the way although this is a php backend going to a mysql database it is working. In fact if I don't use a service and code the http get directly into the controller it all works fine and I see the results as expected.
Please help this is driving me nuts!!

Related

Axios and Blade in Laravel, how ? For Async request category filter

I need to make a category filter for my blog posts. I was toying around with Vue a bit. But since I have not learned Vue, I was recommended to just use Axios. I am completely lost. How does it work? I cannot even log a result from here? I did get it to work with an example in the App.JS from a SO question, trying to find that again. But thats Vue? I am not sure what to do anymore ? This is my example the /axios refers to a controller I show the controller first then the blade :
class AxiosController extends Controller
{
public function index()
{
$articles = Article::all();
//$categories = Category::all();
return response()->json($articles);
}
}
The blade ( I had it without the axios.create and all kinds of try outs I did) I also did it without the #once and the #push I just read this in the Laravel documentation.
#once
#push('scripts')
<script src="https://unpkg.com/axios/dist/axios.min.js">
const instance = axios.create({
baseURL: 'http://localhost:8000/axios',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
const axios = require('axios');
axios.get('http://localhost:8000/axios')
.then(function (response) {
// handle success
console.log(response);
})
</script>
#endpush
#endonce

React APP with Laravel Back End, Can not Insert data

I'm learning to build React JS WebApp with Laravel Back End. I have problem when try to insert data, it seems my insert function in controller is not being called whatever method I try. Here is the code;
The JS:
fetch( '/api/links/', {
method:'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(link)
})
.then(response => {
return response.json();
})
.then(data => {
//update the state of links
});
The /routes/api.php:
Route::post('links', 'LinksController#store');
The /app/Http/Controllers/LinksController.php:
public function store(Request $request)
{
$link = new Link;
$link->title = 'Hard Coded Just For Testing';
$link->url = 'http://but.still/not-inserted-to-database/';
$link->save();
return response()->json(null, 200);
}
My expectation there should be a new record in my Links table, but nothing new inserted.
What did I Miss?? Please Help.
UPDATE:
Event though I set the method to post in fetch options, it turns out when I observe in Developer tools - network tabs, it strangely change to GET method, that's why it never get to call my store function to insert data. Does anyone know what causes this?
SOLVED:
It turns out that because of extra '/' at the end of fetch URL, while in routes/api.php the URL does not have '/' at the end of it, that causing a reroute when original call to /api/links/ with POST rerouted to /api/links with GET. SO simply match the URL perfectly from the route and from the fetch, solve the problem.

Laravel pusher error: JSON returned from webapp was invalid, yet status code was 200

i work on laravel 5.2 and i added vinkla/laravel-pusher to do real time chat app on my site but i faced this issue:
"JSON returned from webapp was invalid, yet status code was 200."
this my controller:
public function authMessageChat(Request $req)
{
$channelName = e($req->input('channel_name'));
$socketId = e($req->input('socket_id'));
$auth = $this->pusher->presence_auth($channelName, $socketId, auth()->user()->id);
return response($auth);
}
this is my script:
var pusher = new Pusher('{{env("PUSHER_KEY")}}', {
authEndpoint: '../auth',
auth: {
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
params: {
id: currentUser.id
}
}
});
var channel = pusher.subscribe('{{$chatChannel}}');
channel.bind('pusher:subscription_error', function(PusherError){
console.log('PusherError' + PusherError);
});
channel.bind('new-message', function(data) {
console.log(data.sender);
)};
Pusher error:
#chrismou Thank you for your answer..
your answer is right and we can implement the solution in another way..
just go to your .env file and make:
APP_DEBUG=false
instead of
APP_DEBUG=true
Thank you
It looks like your app is returning the debugbar html as part of the json response.
Assuming it's the barryvdh/laravel-debugbar you're using, according to the documentation you can switch off the debug bar at runtime:
Config::set('laravel-debugbar::config.enabled', false);
I assume you'll need to add that prior to the response being sent, in the controller method/route you're using for the authentication endpoint (ie, the one you're calling the socket_auth method from)

Reactjs Ajax returns first empty array while getting json object

I have a problem. I am learning React js and I have a template which i must edit. I need to add some ajax methods for getting and sending info. I manage to do some of those actions but now I have a problem.
I have php scripts which is getting me json_encode.
getCategories: function() {
$.ajax({
url: '#########my_url#########',
dataType: 'json',
success: function(data) {
this.setState({datas: data});
}.bind(this)
});
},
and I have this
getInitialState: function() {
return {datas: []};
},
The problem is I always get firstly the empty array and then the result. And when I try to work with it, it gets me error because it tries to map the empty array. This is the console.log before I try to play with the object.
[HMR] Waiting for update signal from WDS...
[]
[WDS] Hot Module Replacement enabled
[Object, Object, Object, Object]
How can I make it to work after the object is full?
First option: render your view on ajax call success
Second option: anticipate the case your state.datas is still empty
for example if you're working in your render function try:
{ this.state.datas ? <div> Loading </div> : <....
Above is JSX syntax
Hope it helps
EDIT:
if(this.state.datas.length == 0) {
var mycomponent =<div> Loading ... </div>;
} else {
var mycomponent = this.state.datas;
}
Basically this should work.

AngularJS and Codeigniter - Combination & Data Transfer

I've recently started learning AngularJS and I was thinking about creating an application using codeigniter as the backend (as an API to insert, update and delete data to a MySQL database) and AngularJS as the frontend framework.
So my questions are: How would I accomplish this? I would I transfer the data between the two?
I wanna know a few details about it with examples because I can't find a good video tutorial where they combine the two. (found some tutorial about laravel & angular, Ruby on rails and angular but not really into those yet).
If someone knows a good video tutorial or even a blog post explaining this, please provide a link.
Found a few combo projects on GitHub but without any explanation what and how it is done, they are not really useful.
The only thing I know about this is that I have to return the data as json but I am not sure how to do that.
Thanks!
Combination of CodeIgniter and AngularJS would help you to build new range of HTML5 Applications.
Unlike JQuery, AngularJS is a front-end framework, which depends on the data from backend, all communications from the front-end happen through a Controller Methods, there are operations for get and post in Angular.
CodeIgniter will act as an API which will output an json response to the Angular controller.
I believe json_encode(data) will output the required JSON string, which upon receipt by front-end, the data presentation layer of Angular takes care of the things /or if you'd like to perform any operation over the data, Angular can do that also.
I don't hold any links for this combination, because most people have shifted towards Ruby on Rails and AngularJS combination, fearing the stop of new release of CodeIgniter
Regret for not having any satisfactory links/blog post.
If time allows me to make a proof of concept, I would be very happy to post the link.
Hope this helps.
EDIT
JSON
[
{"title": "t1"},
{"title": "t2"}
....
]
HTML
<body ng-app="app">
<div ng-controller="MsgCtrl">
<ul>
<li ng-repeat="m in msg">{{m.title}}</li>
</ul>
</div>
</body>
JS
var app = angular.module("app", []);
app.controller("MsgCtrl", function($scope, $http) {
$http.get('/index.php/ctrlname/methodname').
success(function(data, status, headers, config) {
$scope.msg = data;
}).
error(function(data, status, headers, config) {
// log error
});
});
UPDATE
For Insert, Delete, Update using CodeIgniter and AngularJS
CodeIgniter Controller
class Msg extends CI_Controller {
public function retrieveall() { .. } // Retrieves all Content from the DB
public function create(){ .. } // Inserts the given data to DB
public function retrieve($id){ .. } // Retrieves specific data from the DB
public function update($id, $title){ .. } // Updates specific data from the DB
public function delete($id){ .. } // Deletes specific data from the DB
...
}
CodeIgniter Routing
$route['m'] = "msg";
$route['m/(:any)'] = "msg/$1";
HTML
<body ng-app="app">
<div ng-controller="MsgCtrl">
<ul>
<li ng-repeat="m in msg">
{{m.title}}
Delete
Edit
</li>
</ul>
<input type="text ng-model="create.title">
<button type="submit" ng-click="formsubmit"> Submit </button>
<input type="text ng-model="editc.title">
<button type="submit" ng-click="editsubmit(editc.id)"> Submit </button>
</div>
</body>
JS
var app = angular.module("app", []);
app.controller("MsgCtrl", function($scope, $http) {
$http.get('/index.php/m/retrieveall').
success(function(data, status, headers, config) {
$scope.msg = data;
}).
error(function(data, status, headers, config) {
// log error
});
$scope.delete = function($id) {
$http.get('/index.php/m/delete/' + $id).
success(function(data, status, headers, config) {
$scope.result = data;
}
$scope.edit = function($id) {
$http.get('/index.php/m/retrieve/' + $id).
success(function(data, status, headers, config) {
$scope.editc = data;
}
$scope.editsubmit = function($id) {
$http.get('/index.php/m/update/' + $id +'/' + $scope.editc.title).
success(function(data, status, headers, config) {
$scope.result = data;
}
}
$scope.formsubmit = function($id) {
$http.post('/index.php/m/create', {data: create}).
success(function(data, status, headers, config) {
$scope.result = data;
}
}
});
I believe this would help you understand. It's a bare example

Categories