Hi guys I had used this code my AngularJS app to execute a GET request, now I want to use it in Angular I have some problems with update it can anyone help me ?
script :
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("http://---:8080/api/v1/users")
.then(function(response) {
$scope.users = response.data;
$scope.AfficherMap = AfficherMap;
console.log(response.data);
}).catch(function(response) {
console.log("ERROR:", response);
});
html:
<div ng-controller="myCtrl" style="width: 250px;">
<div ng-repeat="user in users" ng-click="AfficherMap(user.id)">
<a>{{user.id}} {{user.firstName}} {{user.lastName}}</a>
</div>
</div>
You can do this in this way...
Make a get function in UserService:
constructor(http:HttpClient){}
getUsers(){
return this.http.get("api_url");
}
Now In your component call this function.
constructor(private userService: UserService){
}
ngOninit(){
this.userService.getUsers().subscribe((res)=>{
console.log(res); // This is your users list...
this.users = res;
});
}
Now In your html
<div style="width: 250px;">
<div *ngFor="let user of users">
<a (click)="AfficherMap(user.id)">{{user.id}} {{user.firstName}-
{{user.lastName}}
</a>
</div>
</div>
AngularJS(1.x) and Angular(2+) are totally different frameworks, in Angular(2+) you will need to use HttpClient module to do an HTTP call more details on the official doc
Find a suggestion for your code:
getUsers() {
this.api.getUsersCall()
.subscribe(users => {
for (const u of (users as any)) {
this.users.push({
name: u.name,
username: u.username
});
}
});
}
given that api is an instance of the APIService you need to create a module for it and declare it in your component class with the specifier private, APIService module will contains the definition of getUsersCall:
getUsersCall() {
return this.http.get("http://---:8080/api/v1/users");
}
Related
I'm trying to integrate AngularJS in my Spring Boot MVC project but I can't understand how to connect it to Spring Boot through #RequestMapping and #GetMapping.
When I get the project locally I don't detect any error on chrome Google Developer Tools.
This is my Controller
var main = angular.module('main', []);
main.component('main', {
templateUrl: 'views/main.template.jsp',
});
main.controller('CaseJson', function($scope, $http) {
$http.get('caseprod/all')
.then(function(response, status) {
$scope.myWelcome = response.data;
}, function(err) {
console.error("Error", err);
});
});
main.controller('getcontroller', function($scope, $http, $location) {
$scope.getfunction = function(){
var url = $location.absUrl() + "caseprod/all";
$http.get(url).then(function (response) {
$scope.response = response.data
}, function error(response) {
$scope.postResultMessage = "Error with status: " + response.statusText;
});
}
})
I tried with both controllers
And this is where it should display:
<div data-ng-controller="getcontroller">
<div var="current" data-ng-repeat="case in response">
<div class="container">
<div class="img-container">
<img data-ng-src="{{data.img}}" alt="">
</div>
<div class="user-info">
<h2>"{{data.nome}}"</h2>
<span>"{{data.annoFondazione}}"</span>
</div>
</div>
</div>
</div>
Here the controller spring
#RestController
#RequestMapping("/caseprod")
public class CaseProduttriciController {
#Autowired
private CaseProduttriciService caseprodservice;
#GetMapping(value = "/all", produces = MediaType.APPLICATION_JSON_VALUE)
public List<CaseProduttrici> findAll(){
return caseprodservice.findAll();
}
If you need something else, tell me. Thanks
spring.datasource.url=dbc:mysql
Is it normal that you miss "j" in jdbc ?
What are showing your logs ?
I'm programming for a college assignment and I've got no idea what I did wrong, so looking for pointers here.
So I'm trying to access events from a database and display them as thumbnails. Where am I going wrong?
HTML Code:
<div class="col-sm-6 col-md-3" ng-repeat="event in EventCtrl.events" ng-controller="EventController as EventCtrl">
<div class="thumbnail tile tile-medium">
<a href="#" data-toggle="modal" data-target="#view-event-modal">
<img id = "eventImg" src="/img/sports.png" alt="Sports">
</a>
</div>
Angular Controller:
angular.module('EventCtrl', []).controller('EventController', function($http) {
$http.get("/events")
.then(function(response) {
this.events = {}
this.events = response.data;
});
});
Node function:
app.get('/events', function(req, res){
eventData = Event.find({}).toArray();
res.render('events', eventData);
});
Your controller should manipulate the $scope, and your view should interact with the scope.
Why don't try something like that
angular.module('EventCtrl', []).controller('EventController', function($scope, $http) {
$http.get("/events").then(function(response) {
$scope.events = response.data;
});
});
I've been struggling with the following problem:
I'm trying to delete a 'Post' item from a Firebase Array with the $remove AngularFire method which I have implemented in a Angular Service (Factory). This Post is a child of 'Event', so in order to delete it I have to pass this Service a argument with the relevant Event of which I want to delete the post.
This is my controller:
app.controller('EventSignupController', function ($scope, $routeParams, EventService, AuthService) {
// Load the selected event with firebase through the eventservice
$scope.selectedEvent = EventService.events.get($routeParams.eventId);
// get user settings
$scope.user = AuthService.user;
$scope.signedIn = AuthService.signedIn;
// Message functionality
$scope.posts = EventService.posts.all($scope.selectedEvent.$id);
$scope.post = {
message: ''
};
$scope.addPost = function (){
$scope.post.creator = $scope.user.profile.username;
$scope.post.creatorUID = $scope.user.uid;
EventService.posts.createPost($scope.selectedEvent.$id, $scope.post);
};
$scope.deletePost = function(post){
EventService.posts.deletePost($scope.selectedEvent.$id, post);
// workaround for eventService bug:
// $scope.posts.$remove(post);
};
});
And this is my Service (Factory):
app.factory('EventService', function ($firebase, FIREBASE_URL) {
var ref = new Firebase(FIREBASE_URL);
var events = $firebase(ref.child('events')).$asArray();
var EventService = {
events: {
all: events,
create: function (event) {
return events.$add(event);
},
get: function (eventId) {
return $firebase(ref.child('events').child(eventId)).$asObject();
},
delete: function (event) {
return events.$remove(event);
}
},
posts: {
all: function(eventId){
var posts = $firebase(ref.child('events').child(eventId).child('posts')).$asArray();
return posts;
},
createPost: function (eventId, post) {
// this does work
var posts = $firebase(ref.child('events').child(eventId).child('posts')).$asArray();
return posts.$add(post);
},
deletePost: function (eventId, post) {
// this does not work
var posts = $firebase(ref.child('events').child(eventId).child('posts')).$asArray();
return posts.$remove(post);
}
}
};
return EventService;
});
When I try to delete the link tag just freezes and no error logging appears in the console. While if I call $remove on my $scope.posts directly in my controller it magically works.. Furthermore my Post is not removed from my Firebase DB.
Another weird thing is that 'CreatePost' works perfectly fine using the same construction.
My view:
<div class="col-xs-8 col-xs-offset-2 well">
<form ng-submit="addPost()" ng-show="signedIn()">
<input type="text" ng-model="post.message" />
<button type="submit" class="btn btn-primary btn-sm">Add Post</button>
</form>
<br>
<div class="post row" ng-repeat="post in posts">
<div>
<div class="info">
{{ post.message }}
</div>
<div>
<span>submitted by {{ post.creator }}</span>
delete
</div>
<br>
</div>
</div>
</div>
P.s. I'm not too sure that my 'Service' is implemented in the best possible way.. I couldn't find another solution for doing multiple firebase calls
var posts = $firebase(ref.child('events').child(eventId).child('posts')).$asArray();
within the Post part of my EventService, because it depends on eventId in each CRUD operation. Any ideas would be very welcome :)
The easiest way for me was to use this:
var ref= new Firebase('https://Yourapp.firebaseio.com/YourObjectName');
ref.child(postId).remove(function(error){
if (error) {
console.log("Error:", error);
} else {
console.log("Removed successfully!");
}
});
The only way I'm able to remove the item is using a loop on the array we get from firebase.
var ref= new Firebase('https://Yourapp.firebaseio.com/YourObjectName');
var arr_ref=$firebaseArray(ref);
for(var i=0;i<arr_ref.length;i++){
if(key==arr_ref[i].$id){
console.log(arr_ref[i]);
arr_ref.$remove(i);
}
}
Hi I'm just learning angular, and I was wondering if someone could let me know what I'm doing wrong with setting up this simple load bar in the Yeoman signup page
In the signup.controller.js, I have the following code:
'use strict';
angular.module('lolBetApp')
.controller('SignupCtrl', function ($scope, $http, Auth, $location) {
$scope.user = {};
$scope.errors = {};
$scope.register = function(form) {
$scope.submitted = true;
if(form.$valid) {
Auth.createUser({
summonerName: $scope.user.summonerName,
email: $scope.user.email,
password: $scope.user.password
})
.then( function() {
// Account created, redirect to home
$location.path('/');
})
.catch( function(err) {
err = err.data;
$scope.errors = {};
// Update validity of form fields that match the mongoose errors
angular.forEach(err.errors, function(error, field) {
form[field].$setValidity('mongoose', false);
$scope.errors[field] = error.message;
});
});
}
};
$scope.$emit('LOAD')
$http.jsonp('http://filltext.com/?rows=10&delay=5&fname={firstName}&callback=JSON_CALLBACK')
.success(function(data){
$scope.people=data;
$scope.$emit('UNLOAD')
});
}).
controller('loaderController',['$scope',function($scope){
$scope.$on('LOAD',function(){$scope.loading=true});
$scope.$on('UNLOAD',function(){$scope.loading=false });
}]);
And in my signup.html, I have the following code:
<div ng-controller="loaderController">
<div class="alert alert-info" ng-show="loading">Summoning...</div>
<div ng-controller="myController">
<ul>
<li ng-repeat="person in people">
{{person.fname}}
</li>
</ul>
</div>
I was able to get this to work easily without using Yeoman, using the code in this link http://plnkr.co/edit/30qbDj0xuBESp6LT8etM?p=info
Does anyone know what I'm doing wrong?
Thanks,
Nevermind! I just got it to work. The problem is that I had the wrong name for the controller in the signup.html page
<div ng-controller="SignupCtrl">
<ul>
<li ng-repeat="person in people">
{{person.fname}}
</li>
</ul>
</div>
I am just a beginner in Angularjs. I have been trying for consuming WebApi service by angularjs. I am following this
1: http://weblogs.asp.net/dwahlin/using-an-angularjs-factory-to-interact-with-a-restful-service documentation. It has been clearly documented about use of factories and services. I want to perform crud operations and I am following the same way but I am not even getting the methods called in the Api controller and how can I get the data to be listed in the view?
I have done this: My factory is defined in index.cshtml
In the Main view ie. Index.cshtml
#{
ViewBag.Title = "Index";
}
<style>
.container {
float: left;
width: 100%;
}
</style>
<script src="~/Scripts/angular.min.js"></script>
<h2>Practising Angular</h2>
List
Edit
<div ng-app="demoApp">
<div class="container">
<div ng-view=""></div>
</div>
</div>
<script>
var demoApp = angular.module('demoApp', []);
demoApp.config(function ($routeProvider) {
$routeProvider.when('/', { controller: 'SimpleController', templateUrl: 'Home/List' })
.when('/Edit', { controller: 'SimpleController', templateUrl: 'Home/Edit' })
.otherwise({ redirectTo: '/' });
});
demoApp.factory('dataFactory', ['$http', function ($http) {
var urlBase = '/api/Customer';
var dataFactory = {};
dataFactory.getCustomers = function () {
return $http.get(urlBase);
};
dataFactory.getCustomer = function (id) {
return $http.get(urlBase + '/' + id);
};
return dataFactory;
}]);
demoApp.controller('customersController', ['$scope', 'dataFactory', function ($scope, dataFactory) {
$scope.status;
$scope.customers;
getCustomers();
function getCustomers() {
dataFactory.getCustomers()
.success(function (custs) {
$scope.customers = custs;
})
.error(function (error) {
$scope.status = 'Unable to load customer data: ' + error.message;
});
}
}]);
</script>
I have this controller which runs by default as it is an MVC 4.0 project and "Home Controller" and "Index" is defined in the route.
namespace Routing_Angular.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
public ActionResult List()
{
return PartialView();
}
public ActionResult Edit()
{
return PartialView();
}
}
}
The List and Edit Action methods are returned as partialviews because they will act as views to render data in angular js.
So, this is what I have in both of the partial views..
List.cshtml
#{
ViewBag.Title = "List";
}
<h2>Listing the users in order </h2>
<div class="container">
Name: <input type="text" ng-model="filter.name" />
<ul>
<li ng-repeat="objCust in customers | filter:filter.name">{{objCust.name }}-{{objCust.city}}
</li>
</ul>
Customer Name:<br />
<input type="text" ng-model="newCustomer.name" /><br />
Customer city:<br />
<input type="text" ng-model="newCustomer.city" /><br />
<button ng-click="addCustomer()">Add customer</button>
</div>
Edit.cshtml
#{
ViewBag.Title = "Edit";
}
<h2>Edit the particular user. Things are under construction</h2>
<h2>Listing the users in order </h2>
<div class="container">
Name: <input type="text" ng-model="city" />
<ul>
<li ng-repeat="objCust in customers | filter:city">{{objCust.name }}-{{objCust.city}}
</li>
</ul>
</div>
This is the Api controller/Service that is being getting called from Factory in the index.cshtml. But none of the methods are getting called. How the data got from the factory objects will be shown in the View?
ApiController
namespace Routing_Angular.Controllers
{
public class CustomerController : ApiController
{
//
// GET: /Customer/
public HttpResponseMessage Get()
{
CustomerService ObjService = new CustomerService();
var Clients = ObjService.GetClients();
if (Clients.Count < 1) throw new HttpResponseException(HttpStatusCode.NotFound);
return Request.CreateResponse<IEnumerable<tblreferralService>>(HttpStatusCode.OK, Clients);
}
// GET api/customers/5
public HttpResponseMessage Get(int id)
{
CustomerService ObjService = new CustomerService();
var Client = ObjService.GetClient(id);
if (Client == null) throw new HttpResponseException(HttpStatusCode.NotFound);
return Request.CreateResponse<tblreferralService>(HttpStatusCode.OK, Client);
}
}
}
Below I am attaching the image for project structure. It is just a basic structure.