How do frameworks such as AngularJS route requests - javascript

Many web frameworks such as AngularJS support "routing" whereby the user can visit the website, and have a template displayed to them based on their request URL. But these frameworks are entirely frontend JS, just simply a 'script src' import, so how does it manage to capture all requests to the website, and then redirect to a js file for processing, etc.
Any response is appreciated, since I have been trying to work out how exactly these frameworks execute the 'capturing' part of routing for some time, but with no luck.

Let me give you a simple model for it.
We can grab the current URL. We can then break that string and we can get different parts separated by '/' Based on which we can put condition which page and what data to show. And when we have decided that we can load our desired page using ajax.
For example my current url is https://www.example.com/module I can get "module" out of this url and then I can load inside the body of my page
$('body').load('module.html');
The following code is from my current work. See how different urls are captured and routed to my specified document. I also get the data from url to use into my ajax requests etc.
app.config(function($routeProvider) {
$routeProvider.when("/", {
templateUrl : "home.html"
}).when("/logout", {
templateUrl : "logout.html"
}).when("/course/:id", {
templateUrl : "course.html"
}).when("/course/:courseId/assignment/:assignmentId", {
templateUrl : "assignment.html"
});
});

Related

angularjs route to match $window.location

I want to reload the page with different html page using angularjs $window, the documation says:
Page reload navigation
The $location service allows you to change only the URL; it does not allow you to reload the page. When you need to change the URL and reload the page or navigate to a different page, please use a lower level API, $window.location.href.
So I set the loaction to the page $window.location.href = '/transaction';
and the matching route on config block:
app.config(function($routeProvider) {
$routeProvider
.when('/transaction', {
templateUrl : 'JavaScript/directives/modelHTML/Transaction.html',
controller : 'endProcessModelController'
});
});
But instrad of Transaction.html page I get Error 404: SRVE0190E: File not found: /transaction with the route mydomain.com/UI/transaction.
BTW - templateUrl url's works fine in other place like UImodel so the problam is the navigation I think.
Set the location to the page $window.location.href = '#/transaction'; .
'#' indicating location the startpage which is normally index.html. so the link will be index.html#/transaction.Since its a single page app
i think in your config do
'/UI/transaction' instead of `/transaction`
and in the link do $window.location.href = '#/UI/transaction'
Is the mydomain.com/UI/transaction address correct (you use html5 mode)?
Does the problem occur when you try to enter directly into mydomain.com/UI/transaction?
If so, the problem is wrong server configuration (eg .htaccess file).
Try this
$location.path($window.location.origin +'/transaction');
And if you feel all the routes have something extra after the origin you can set a <base href="..."> for that and tell angular from where to take the rest amount of text for route purpose.
If you redirect the page with your_origin/transaction your browser will make a request to the server of /transaction, which the server will be not able to understand and 404 will come. But the route is client side (browser) routeing, so If you are routing to route /abc your javascript code is interpreting that, and invokes the corrosponding operations, (might be a different call to server for the html template or some data dependency, and then instantiating the controller and attach to view). So the moment you are trying to route your javascript code should be loaded.
Either you go for a ui-router where the route comes after # and this allow the browser to play after the text of (#) and not to reloading.
Or, make your server such a way, If a unidentified request comes you should return the base (index) page, so it will load all the scripts and that js will do the rest. (But obviously you will loose all the existing data in that state)

How to properly routing for SPA using Angular 1.5?

I'm new to angular. I create a blog for showing my profile.
In my website, I have several component and my app.module has a configuration for the routing, as shown:
app.config(function($locationProvider, $routeProvider){
$locationProvider.html5Mode({
enabled:true,
requireBase: false
})
$routeProvider.
when("/", {
template: "<research-overview></research-overview>"
}).
when("/research-interests", {
template: "<research-interests></research-interests>"
}).
otherwise({
redirectTo: "/"
})
});
Here is an example of my component:
angular.module('researchOverview', [])
.component('researchOverview', {
templateUrl: '/templates/research-overview.html',
});
I tried to locally run the server using python -m SimpleHttpServer
so that I can access my local website using browser to localhost:8000, When I click a link from my homepage, the page is correctly loaded. However, when I initially access my website using different urls (e.g. localhost:8000/testing) Angular route doesn't seem to work properly.
I get this error instead,
How do I set the router so that those urls can be redirected to my homepage?
Given you have enabled html5 mode I think you may need to set your server up so that regardless of the path it will return your index.html file.
For example, when your server receives a request for a resource at localhost:8000/testing it will return index.html.
From the AngularJS documentation:
Using this mode requires URL rewriting on server side, basically you
have to rewrite all your links to entry point of your application
(e.g. index.html). Requiring a tag is also important for this
case, as it allows Angular to differentiate between the part of the
url that is the application base and the path that should be handled
by the application.

need understanding for Angular routing's when method

Hi All I am new to angularJs , I am finding it hard to understand the routing concept, I learnt from many sources , but still it's not quite clear specially the when method. What i understood is routing helps us to achieve single page application , which means browser loads only one .html file and then other contents are removed or added based on user's interaction, no other file gets loaded. But in the following definition from the link angular routing
templateUrl: When the HTML to be displayed is complex and large, it’s better to break them into separate templates/files, and give the URL to the HTML file as the templateUrl. AngularJS loads the HTML file from the server when it needs to display the particular route.
It says angularjs loads the HTML file as the templateUrl. Could someone please explain this to me ?
1.The templateUrl property tells which HTML template AngularJS should load and display inside the div with the ngView directive.
2.It can be path (or) function and .when() method takes a path and a route as parameters.
3.It can be use as function with returning generated URL. We can manipulate url with passing argument which takes route.
.when('/:screenName/getAll',{
templateUrl: function(route){
return route.screenName +'/getAllList'
}
})
So, it is not like reloading the whole html page.Only the html content is loaded inside the div.. Hopes this help.!!!
For example:
//main.js
$routeProvider.when('/computers', {
templateUrl: 'views/computers.html',
});
//./views/computers.html
<ul>
<li>Computer 1</li>
<li>Computer 2</li>
</ul>
When the route is http://example.com/#/computers, AngularJs will loads the ./views/computers.html file by ajax, and cache it for the others requests. So, it's not only one (the main) html file that will load in your SPA.
Angular loads the html file as the template url means that it use the path you provide to load the html. This would be more organized compared to writing the html in angular components.
Single page app does not means angular loads just only one file. When users interacts, routing may be executed, more data will be loaded, and more html or some portions of html will be loaded combined with data to render to users.
The "when" method means that when users visit a defined route, things followed will be proceed, including the "templateUrl".

Handling Dynamic Routes Without a Server

Is it possible to serve a dynamic html page without a backend server or without using a front-end framework like Angular?
Edit
To clarify, the index file is served from a backend. This question is about how to handling routing between the index and dynamic pages.
I have an application that consists of two files - index.html and dynamic.html. When the user clicks an option say "Option A", they are served dynamic.html and the url is updated to /option-a. Now, with a server this is no problem and assuming the user visits the app from the landing page, it isn't a problem either because a cookie can be set. However, suppose a user visits a page at my-domain/option-a. That route doesn't exist and there is no server to redirect so it will 404. They would have to visit dynamic.html.
I think this architecture demands that there's either a server to handle route redirects or a SPA framework.
Is there something I'm missing?
your SPA framework will be active only once your HTML page is loaded and to do that you need to redirect any URL that user tries for your domain to that HTML file. For this you obviously need a server (and since you are talking about my-domain/option-a I assume you have atleast a basic server). You can refer to this link to get an idea on how server can redirect a URL to specific html file: Nodejs - Redirect url.
Once HTML is loaded you can initialize your SPA framework and decide the template to be loaded based on the URL.
Note: without a server you will access URLs using file://somepath/index.html and anything other than this URL will result in 404 and no SPA framework can handle that.
I think the solution is to use a static site generator such as Jekyll or Middleman and allows you to convert information into static pages. That way you functionally are building a bunch of pages but they are all compiled ahead of time. You can add dynamic content that is loaded in from a yaml file and it will compile the content into separate html pages.
It is not possible, but there is a workaround using url parameters like this:
my-folder/index.html
my-folder/index.html?=about
my-folder/index.html?=about/sublevel
my-folder/index.html?=profile
my-folder/index.html?=./games
const urlParams = new URLSearchParams(location.search);
const route = urlParams.get('');
console.log(route);
// Should print "about" "about/sublevel" "profile" "./games"
Of course this approach is not as clean as using a server for routing, but it's the best you can get without a server.
BTW. I tried an alternative solution creating symlinks with all the target routes pointing to the same index.htmlfile. But it did not work because the browser (firefox) redirects by default when it finds a symlink, thus home is shown all the time.

AngularJS $routeProvider can't load directly to partial

At the minute I'm currently using the $routeProvider to dynamically load sections of the page like so:
$routeProvider
.when('/', {
templateUrl: '/pages/home.html',
controller: 'mainController'
})
.when('/our-business', {
templateUrl: '/pages/our-business.html',
controller: 'businessController',
css: 'css/_business.css'
})
.when('/solutions', {
templateUrl: '/pages/solutions.html',
controller: 'solutionsController'
});
Currently, if I go directly to the index (localhost) and then select 'Our Business' from the navigation menu then Angular handles the location request and the page loads fine, with the URL changing to localhost/our-business. If I then reload, or open this URL directly I get a 404 error - presumably because Apache is trying to open our-business.html which doesn't exist. If I open localhost/#/our-business then the index is loaded and Angular then handles the request. The issue I've got is that this is designed to be a public facing website, so if a user were to copy and paste the URL or share it via email, they'll get a 404 error.
Is there any way to have Apache rewrite URLs to parse them via the index and AngularJS so that we can keep the non-hash style but still have functional URLs?
As said Kailash you can set the locationProvider to html5 mode
$locationProvider.html5Mode(true)
when you bootstrap your angular application.
Then you have to tell your Apache server to send the index.html (entry point of you single page app) for any requested url.
The angular router will then handle the proper route
Nope. Changing the url without the hash reloads the entire page.
The entire point of this $routeProvider is to build single-page app with multiple views.
Basically, having the # in the url is the only way to do that. Changes to a url's hash don't result in a page reload, and allow Angular to load the relevant views.

Categories

Resources