My Angular app is splitted into several subapps. I'm working with laravel which is also responsible for the routing between the subapps.
So there are the following urls handled by laravel:
ModuleX: /moduleX
ModuleY: /moduleY
ModuleZ, Item n: /moduleZ/item-n (unlimited amount of items)
And finally on top of these there are my 3 Angular subapps.
So for example: /moduleZ/item-1/#/hello/world
Additionally the templates, partials and a RESTful API are served by laravel under the following urls:
/templates
/partials
/api
If I set the base url with the html tag <base href="http://www.example.com/app/"> I can use relative urls for templates, partials and the api but not for the routing. I'll allways have to add the module url part like that moduleX/#/hello/world.
If I set the base url like for example <base href="http://www.example.com/app/moduleX/"> I can write all links like #/hello/world but the templates, partials and api requests aren't working anymore.
The whole app also sits in a subfolder so I can't just use for example /templates.
So basically my problem or the question now is, what's the best way for handling the different base urls? I don't really like it to prepend the module name to every link.
Look it's might be a particular solution, but may be you should use filters for urls?
For example:
.filter('routeFilter', [function () {
return function (route) {
if (some condition mean this direct html link){
return 'MODULE-X/' + route;
}else{
return route
}
};
}])
I would suggest you let (sub-)apps know their real base not the parent's one, but you make the server responsible for climbing the path hierarchy to find higher level shared resources for missing local ones. This also makes it very easy to prototype new sub-apps, test changes to common pieces independently first, etc.
In a webserver like Apache, this would look like a rewrite rule (conditional on not finding a file) it just substitutes the same file in the parent hierarchy.
In laravel (according to the router docs) it looks like you can add optional 'directories' to your current rules, i.e.:
Route::get('/.../app/templates/{name}', function($name)
...
becomes:
Route::get('/.../app/{module?}/{item?}/templates/{name}', function($name, $module, $item)
...
You could then use $module and $item if you need to test a resource change with specific sub-app/items.
The drawback in making the server responsible for handling inheritance is the independent client fetch/cache of identical resources with different paths. But you can at least choose between large file inefficiency or access latency by using either rewrites or redirects. You can also always hardcode significant paths in production clients later and still benefit from having a hierarchy for testing and graceful handling of occasional errors in client side links.
You can do it in a simpler way if you use combination of service and directive.
You can implement a directive similar to ngHref which when given a link will transform it and append the given link back. It will be injected with a service which will give it the base url or relative url or anything module specific.
This service which is injected in directive will be configured using serviceProvider in app.config block of each sub-app. Since angular injector have only one instance of each service I think you will need more than one injector or one injector per sub-app. Its unclear whether they share injector among them in your app.
You can configure each service according to module to return different base paths. Which will be appended by directive to each link every time.
With this you can use <base href="http://www.example.com/app/"> and that should solve your problem.
I haven't written any code but I can help if you need it.
Related
I have an angular site hosted in S3, and I have a 404 route set up (I use hash), if someone for example does
mysite/#/gibberish
goes to
mysite/#/404
and on the s3 bucket we have a redirect rule in place for
mysite/gibberish
goes to
mysite/404.html
all is well
Now I just want to add an extra logic on top that if someone types in
mysite/customerid
which is a 404 to somehow redirect this to an angular controller so I can send this request to right page.
So somehow in my redirect in S3 rule add a reg exp for some incoming request and rather than serve 404.html send it i.e. mysite/#/handlethis
Is this possible ?
Depending on the router of your choice, you could do something like the following (which is what we've done (well, not precisely this, but close)):
ui-router
app.config(function ($urlRouterProvider) {
var regx = /\/#\//; // match against /#/
$urlRouterProvider.otherwise(function ($state, $location) {
if (!regx.test($location.path()) { // if no match
$state.go('customHandlingState', /** params **/, /** configuration **/ });
// Transition to your custom handler state, with optional params/config.
}
});
});
You could pair this up with custom stateChange[Start|Stop|Error|Success] handlers in the run block of your app to customise it to your liking.
I would supply an example of how to do this with ngRoute, but I gave up on ngRoute two years ago and haven't looked back since. As such I have no suggestion to give, nor was I able to find a solution to the problem you present.
I would strongly suggest you scrap the S3 portion of this recipe as it will make your life a lot easier when it comes to client side routing (speaking from personal experience here, it's my opinion on the matter - not fact) and handle your 404's/500's on the client with custom state handlers.
If need be you could hook into some logging service and store some data whenever a client/person ends up in an erroneous state.
I suppose my 'counter question' is; What do you gain from using S3 redirect rules? So as to get a better understanding for the needs and goals here.
Some reference material to go along:
ui-router#$state.go
ui-router#$urlRouterProvider.otherwise
I would suggest using routeParams
https://docs.angularjs.org/api/ngRoute/service/$routeParams
the route would look like this:
/mysite/:cid
then access the id with the controller:
$routeParams.cid
I hope this could help
You can manually configure your server to always serve your index.html(your main html file which includes reference to angular script) on all incoming http requests. Client routing will be handled by Angular
My current setup is as follows:
Starting the server and going to localhost takes me to home.ejs as stated here (in my front end routing):
However, when I go to localhost:3000/posts, the posts template is infact not being injected into my index file (where my ui-view is). Ive been following the mean stack guide from thinkster, but have been making a few changes (not using inline templates)
My question is, how do I setup my routing such that localhost:3000/posts will actually take me to the posts page?
You are dealing with two types of routing, client side and server side. Client side is located in your app.config function in your angular code. That function should be calling html files, which are located in your public directory. These files are not rendered server side via express and they wouldn't not be able to read the ejs format.
Typically with MEAN stack applications, you just render your index file when the user logs in, and from there the Angular router takes over with html files and you handle your routing from there. If you don't want Angular routing, you have to set up your index.js file to render pages as they are called with res.render('posts')
You can change your posts.ejs file into an html file, and just call it via Angular when the user navigates to localhost/#/posts (depending on your version and configuration of Angular).
Your Express server side routing will handle your API calls as you have defined in index.js. In order to call those APIs, you will make GET or POST requests via Angular's $http method, through a service or factory.
Hope that helps, if not, let me know and I can elaborate or provide examples.
To solve this, I used Eric Hartmanns solution. By changing posts.ejs to posts.html, and letting the angular router take over on client side, the page was being rendered. However, when typing in localhost:3000/posts in the address bar, the page wasnt being rendered and the server was being hit for some reason. To get around that I simply made a new get route in express and re-rendered index whenever that route was hit like so:
router.get('/', function(req, res) {
res.render('index');
});
When routing in Angular views we add the following. I don't understand the need to add #; if I remove it, I get a 404 Error.
a href="#/AddNewOrder"
Putting # in URL indicates start of the hash part, which is used to address elements inside a single page. In modern single-page web applications, this can be used to address application states.
If you don't put the # there, you're changing the path, which means you're creating a new URL and prompting the browser to load the content at that new URL instead of the current page.
As other posters have suggested, you don't have to use hashes when using html5mode. I left it out, because it brings a few challenges of its own, which I feel to be outside the scope of the question.
enter link description hereYou don't have to. You can configure your URLs to look like normal URLs, but in reality they will still work the same way.
Check https://docs.angularjs.org/guide/$location
And refer to html5mode
It will only work in modern browsers though. Old browsers will still show the hash. But the cool thing is that you can write your URLs the old/normal way.
# or fragment identifier is a way to indicate a specific portion of a single document. Without the #, the url corresponds to a different page.
For example www.yoursite.com/page links to the /page location of your website, while www.yoursite.com/#/location points to the same index page of your website but at a specfic point in the web page #location, or in your case, a different template view.
Angular routing can not load different templates for different server urls. It is specifically designed for single-page applications and any loading of partial views or templates has to happen on the same web-page or location. Hence only the fragment part of the url changes when using angularjs routing.
More information about fragments can be found here: http://en.wikipedia.org/wiki/Fragment_identifier
Currently I am combining a traditional application with some dynamic parts written using AngularJS. I would like to provide some configuration from my server to my module. In this case I would like to configure the application 'base' URL. All templates can be found at a specific location and this location is determined by the server.
So I tried something like this:
angularForm.config(
function($routeProvider, TemplateLocator) {
$routeProvider.when('/', {
controller : TestController,
templateUrl : TemplateLocator.getTemplate('FormOuterContainer')
});
});
At the server:
<script type="text/javascript">
angular.module('BoekingsModule.config', []).provider('TemplateLocator', function() {
this.$get = function() {
return // something
}
this.getTemplate = function(name) { return 'location...'; }
});
</script>
However, I am not sure this is the right way.
So in short: how can I provide some (external) configuration to a module without having to change the module itself?
There are several things you can do
Render the locations in the js on the server.
Pro: less requests -> better performance (usually)
Cons:
combining server side rendering with an SPA makes the system more complex, leading to higher maintenance costs.
it is harder to properly compress your js files if you want to mix in server side rendering, embedding js in html is also ugly.
Extract the template location to a service.
From this service you could use a $resource to fetch the data from the server in json format. This keeps things simpler, but it could also increase your web server's load.
Wow it has been a long time since. I completely forgot about this post.
So, in the end I decided it was better to use another approach. Like iwein said, combining SPA with server side rendering makes the application a lot more complex. Therefore I extracted the SPA part into a separate application which in turn is referenced from (in my case) the JSP.
When my module needs some additional configuration, it gets it using a REST API. This way the SPA part of the application is completely decoupled from the server-side rendered part.
I am planning to rewrite my site into CakePHP and after having spent a full week on learning it, I am still not sure how to do good custom routing in CakePHP.
This is what I want:
Keep the current url structure in www.domain.tld/en/dragons.html, or use a www.domain.tld/en/dragons, but not www.domain.tld/en/nodes/dragons.html. And also be able to use controllers on a similar path structure.
There are about 100 static pages on the entire site. I have read into multi-language routing and I think I can do it. I can also make /en/* or /en/:slug route via a PagesControler or a self-written NodesController.
My problem is that I would like to be able to mix and match url's with and without controllers, so actually what I want is that it checks if a :slug is part of the slug-list, there should still be the option to use that url with a controller.
I have created routes for both /en/contact and /en/:slugid, but it seems all queries were routed to my NodesController, even while I explicitly said that /en/contact should be routed to the ContactsController.
How can I instruct Cakephp to keep my current dictorary structure? I read the routes part of the Cakephp book, but it was extremely short and made me a little unsure about the possibility of such routing. If necessary, I'll just write a php-code that prints all routes for all slugs, so I can still write controller-routes with a similar path structure.
If a file exists in webroot (ie. app/webroot/static.html), the .htaccess file will tell Apache to serve that file before loading the CakePHP framework for requests to www.example.com/static.html.
Cake loads routes in a top-down order and will use the first matching route to handle a request. In your case, /en/contact should be above /en/:slugid, else the slugid rule will always win.
If CakePHP's routing does not accomplish what you are after, you can always implement a custom route class (book / example).