SPRING-DATA-REST Backend with AngularJS frontend - json

Is there any frontend application sample that consumes RESTful services of Spring-data-rest backend which is written with angularJS.

My prefer for rest api for angularjs is RESTANGULAR module...
In the site you can see many examples that how they deal with Rest calls and really good documentation and good community as well...
In this example which is from spring example SPRING.IO they uses $http, but I should say that Restangular uses $http as well, so basically you can say that Restangular is extended version of $http...
and for the last you can look for $resource...
I will update my answer If I will find something new...

Here are some links to AngularJS apps consuming Spring RESTful services
https://github.com/spinner0815/spring-data-rest-angularjs

At the moment, I think that angular-hal is the best library to consume Spring Data Rest output and stay with its philosophy of discovering url through relations.
The home page: https://github.com/LuvDaSun/angular-hal
and some examples :
https://github.com/LuvDaSun/angular-hal/tree/master/demo (by the dev)
https://www.jiwhiz.com/blogs/Consume_RESTful_API_With_Angular_HAL
https://github.com/paulcwarren/gs-rolebased-ui-with-hypermedia

here has a nice lib spring-data-rest-js can help you.
It's a easy to use and lightweight javascript lib can run in both node.js and browser. After use this lib you can manage entity like this way:
let springRest = require('spring-data-rest-js');
let Student = springRest.entity.extend('students');
let student = new Student();
student.set('name', 'Tom');
//create entity
student.save().then(()=> {
//update entity
student.set('name', 'Physics');
retuen student.save();
}).then(()=> {
//delete entity
retuen student.delete();
}).catch(err=> {
done(err);
})
base on fetch API and Promise,inspired by Parse.
It can be work with lib like AngularJS React Vue...

Related

Generate Razor HTML emails in dotnet core 2

How can you generate emails (html) using Razor in dotnetcore - and not from an MVC app (think from a console app)?
RazorEngine does a great job in .net 4.x, but is not working in dotnet core.
RazorEngineLight works in dotnet core 1.x, but not in 2.x.
Some other options are mentioned in this post: Using Razor outside of MVC in .NET Core but none of them actually work in .net core 2.0
Edit two years later:
In case somebody comes here looking for answers on this... I (OP) have stopped entirely relying on Razor to generate emails using templates etc. It is very fragile and error-prone - a non-stop headache. I prefer Mandrill or Sendgrid these days - using templates.
In a comment on this provided answer from the link provided you stated
I am not able to get this to work. I get the error: Unable to resolve service for type 'Microsoft.AspNetCore.Mvc.Razor.IRazorViewEngine' while attempting to activate 'Mvc.RenderViewToString.RazorViewToStringRenderer'.'
This normally indicates that a required service was not registered with the service collection so the provider is unable to resolve the service when needed.
That answer did not refer to the additional service configuration and only had
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IViewRender, ViewRender>();
}
as it was already being run in an Asp.Net Core environment, which meant that the services manually added in the console application were already being done in start up.
Pay attention to this snippet from the answer that was linked to from the answer you commented on.
private static void ConfigureDefaultServices(IServiceCollection services) {
var applicationEnvironment = PlatformServices.Default.Application;
services.AddSingleton(applicationEnvironment);
var appDirectory = Directory.GetCurrentDirectory();
var environment = new HostingEnvironment
{
WebRootFileProvider = new PhysicalFileProvider(appDirectory),
ApplicationName = "RenderRazorToString"
};
services.AddSingleton<IHostingEnvironment>(environment);
services.Configure<RazorViewEngineOptions>(options =>
{
options.FileProviders.Clear();
options.FileProviders.Add(new PhysicalFileProvider(appDirectory));
});
services.AddSingleton<ObjectPoolProvider, DefaultObjectPoolProvider>();
var diagnosticSource = new DiagnosticListener("Microsoft.AspNetCore");
services.AddSingleton<DiagnosticSource>(diagnosticSource);
services.AddLogging();
services.AddMvc();
services.AddSingleton<RazorViewToStringRenderer>();
}
The important part above is
services.AddMvc();
That will add the relevant view engine dependencies to the service collection
MvcServiceCollectionExtensions.cs
public static IMvcBuilder AddMvc(this IServiceCollection services) {
//...code removed for brevity
// Default framework order
builder.AddFormatterMappings();
builder.AddViews();
builder.AddRazorViewEngine();
builder.AddRazorPages();
builder.AddCacheTagHelper();
//...code removed for brevity
}
Everything else as currently presented is sound and should work as intended.
You should review
https://github.com/aspnet/Entropy/tree/93ee2cf54eb700c4bf8ad3251f627c8f1a07fb17/samples/Mvc.RenderViewToString
and follow a similar structure to get the code to work in your scenario. From there you can start making your custom modification and monitor where it breaks.
The modular nature of .Net Core allows for such customizations as the different modules can be stripped out and used in other environments.

How to design correctly a web app in sails.js?

I build a web app using sails.js and I have few questions about the design of the app:
Should I create controllers for each page, component, or model? I saw in the documentation and at some tutorials that they create controllers for each model. That looks nice but if I have a complex page/component and I want to create view with multi models (and data) it doesn't help me.
Where should I put the business logic part of a component or feature? I read about Serivce but I'm not sure that this is the right place.
To sum up, I saw that in sails the code is arranged like the models (you have model, controller and view for each model) but what if I want to arrange it by features or components or pages?
Thanks!
Basically you should have Controller for each Model (but if you don't need specific controller and it would be empty you don't need to create it). It's just a good practice to have a Controller for each Model.
If you use some part of code in many places and it is not connected with one specified Model it should be Service (like sending emails, notifications, logging, images processing). Read about DRY
Controller should be as simple as possible. It should contain call of Model and Service and callback with rendering output. All business logic should be in Models.
I created some additional 'helper' Models for more complex Models like Users or so to make Classes bit shorter.
To sum up. Core of your application is Model. It's not only responsible for database layer, bur also business layer of your app. Later there is Controller. It gets data from Model and it passes it to Views which is responsible for presentation of data taken from Model.
Answer to First
Sails is for REST API it has nothing to do with view.
you just need to know what MVC is and what REST is....
In one Controller you can invoke multiple models or one model can be invoked in multiple controllers.
In one page you can fetch data from two different API's which may be from different controller or Even they can be of different server.
for Example:
In the page you are getting data directly from ellasticsearchAPI(say esAPI1)
You are getting data from sails API(sAPI1).
You are getting data from other sails API(sAPI2).
Answer to Second
For neatness you should try to keep controller as clean as possible. So for the same sailsJS provide you services. Where you can write Common functionalities which are to be used in multiple controllers.
See the codes for example
Codes
here is the controller:
//TestController
module.exports = {
action1:function(req,res){
Model1.find().exec(function(err,data1){
if(err)
return res.negotiate(err);
res.ok(data1);
});
},
action2:function(req,res){
Model2.find().exec(function(err,data1){
if(err)
return res.negotiate(err);
res.ok(data2);
});
},
action3:function(req,res){
var hash=SomeService.getMeHashCode(req.query.text)
res.ok({hashedData:hash});
}
};
And this is service.
//SomeService.js
module.exports = {
getMeHashCode:function(strinToBeHashed){
var hash=doSomeThingToHash(strinToBeHashed);
return hash;
}
};

How to get BreezeJS to talk to MySQL DB with Angular + Node?

Stack: MySQL + Express + Angular + Node and node-mysql to talk to the DB.
EDIT: I'm connectiong to a local DB and the connection works. I can't get Breeze to communicate with it.
I'm trying to get the Breeze Todo app to work with this setup but I'm getting a localhost:3000/ToDos? 404 (Not Found) when Breeze goes out to get the data.
Do I need to create the API for Breeze to talk to? I've tried this:
angular.module('mysql', ['ngResource']).
factory('ToDos', function($resource) {
var ToDos = $resource('/ToDos', {}, {update:{method:'PUT'}});
return ToDos
});
And then injecting it into the datacontext service here:
angular.module('mainApp').factory('datacontext',
['$http', 'logger', 'breeze', 'ToDos', datacontext]);
function datacontext($http, logger) {
var dataService = new breeze.DataService({
serviceName: '/ToDos',
hasServerMetadata: false
});
var manager = new breeze.EntityManager({
dataService: dataService
});
...
}
I'm pretty lost as to what I'm doing wrong. Any help would be appreciated.
EDIT: The comments informed me that the backend API needs to be created. I'm working on that but could use some help converting the breeze-mongodb module.
In Breeze's zza example in repository.js there are calls to this module's MongoQuery() and MongoSaveHandler() functions. Would it be as simple as converting them to MySQL connection.query? And any help in the conversion would be much appreciated!
I'm very curious about your progress on this. It's quite ambitious.
Ultimately I believe you'll be writing something like the "breeze-mongodb" npm module which will have a query and save implementation attuned to MySQL.
It could be tricky without an ORM. If you choose to go with an ORM in Node for MySQL (node-orm???), you can learn a lot about what to do from the Breeze source code for ContextProvider, ContextProvider.EF and ContextProvider.NH in the "breeze.net.server" repo on github. You don't have to be a C# person to glean transferable insights from that code base.

Angular - building a "public" function (newbie)

I'm After several days learning angularJS through converting my standart JS app to a ng one.
I was wondering about this simple scenario:
I have a global function called fb_connect(),
it can be used from any page (or any controller if you like) to make a facebook-based login.
This function makes a simple http call and receives a JSON object contain data to move on (display a pop up, login, etc...)
I read that I can define a Factory or a Service for my app and use it in any controller, which works fine.
So, I created a fb_connect factory function.
The problem is that now, in every page (every controller), I have to define that fb_connect in the constructor of every controller - for example :
function welcome($scope,fb_connect){});
What is the proper way to do this kind of actions using Angular without having to define these functions each and every time in every controller?
Thanks
Setting up factories and services is all part of the dependency injection system of Angular. Using that system is great when you need to create things that depend on other injected things. It's a big tree of dependencies. It's also nice for creating singletons, such that everywhere in your code end up using the same instance of some object.
It sounds to me like neither of these benefits apply in your case. I'd suggest just not using Angular's DI for it. You have some function defined globally, just call it directly and skip the DI. There's nothing wrong with that.
Of course you say it makes an Ajax call, so doesn't depend on the Angular $http service?
Your two options are:
Declare the function on the $rootScope
Inject it as a service
My advice is to go with making it a service. The whole purpose of services is explained in the Angular.js docs, just like this quote:
Angular services are singletons that carry out specific tasks common to web apps... To use an Angular service, you identify it as a dependency for the dependent (a controller, or another service) that depends on the service.
As you mentioned in your question, you'd prefer to not define the service in every controller you wish to use it in. With $rootScope you'll be injecting that also in every controller. So really it's a question of which you prefer, although to answer your question, the proper way of using a factory or service is to inject it into the controller you wish to use it in.
You can always put it in the $rootScope
myApp.run(function($rootScope, fb_connect){
$rootScope.welcome = function(){
};
});

Grails with JAX-RS vs UrlMappings for RESTful Services

I started out looking at the JAX-RS plugin for grails and thought that was the way to go mainly because it was based on JSR-311 and I figure following standards is usually the smart thing to do. However, using Grail's UrlMappings it seems I basically achieve the same thing. I figure I'm missing something, however, we aren't doing anything overly complex. We basically just need to expose CRUD via an API. Example of doing the same thing with both versions:
JAX-RS:
#PUT
#Consumes(['application/json'])
#Produces(['application/json'])
Response putUser(User user) {
user.save(flush:true)
ok user
}
Grails:
def update = {
def user = new User(params['user'])
user.save(flush:true)
render user as JSON
}
Obviously, this is an overly-simplified example and like I said, maybe I'm missing something important. Also, the nice thing about the Grails built in mechanism is I can utilize Content Negotiation along with it.
Anyone have any opinions on this?
I had to make the same decision, and I found it just easier to use URL Mappings because the API was not that complex and there were a limited number of API calls that needed to supported.
If came down to what would be easier to maintain based on the LOE and the resources able to support the implementation.
The jax-rs plugin is very useful if you are creating web services straight to your domain models. It gives you a "generate-resource" command that automatically creates CRUD apis for your model.
grails generate-resource mydomain.Model
This part seems to work fine, however, I encountered quite a few bugs/problems with the plugin that I finally had to implement the REST services using URL-mappings.
Although the URL-mapping method seems to be more coding, it works perfectly.
import grails.converters.JSON
class ModelServiceController {
def id = params.id
def myModel = MyModel.findById(id)
render myModel as JSON
}
Here's the link for grails REST
http://grails.org/doc/1.0.x/guide/13.%20Web%20Services.html