Obtain last part of url path using AngularJS - angularjs

When my app first loads I would like the obtain the last part of the url path. I use this token in order to perform requests, I am currently not using partials since its overkill for my needs. I am currently attempting to extract the path on my controller using the $location.path() method but it returns an empty string.
Here is my simple logging function
$scope.obtainTitle = function(){
var path = $location.path();
console.log($location);
console.log($location.path());
console.log($location.url());
console.log($location.hash());
$scope.title = decodeURIComponent(path);
};
Here is the output, I am serving my site from c9 which is why I blocked out host.

Related

pass relative url in signalR hub connection

I am trying to implement signalR in angularJS,
I want to pass relative url to hub connection, but it's making current url (on which my angular application is hosted)
My API base url : http://localhost:81/NrsService/api/TestSignal
My angular application running at
http://localhost:81
Here is my signalR setup :
$.connection.hub.url = "/NrsService/api/TestSignal";
//Getting the connection object
connection = $.hubConnection();
Like it is sending request at http://localhost:81/signalr/negotiate? but I want it to be http://localhost:81/NrsService/api/TestSignal/negotiate?
You have to edit the generated JavaScript code where the client proxy is defined. As of SignalR 2.4.0 there is a createHubProxies function defined where you should find this line of code:
signalR.hub = $.hubConnection("/signalr", { useDefaultPath: false });
Change it to the following to prevent the "/signalr" ending in your requests:
signalR.hub = $.hubConnection("", { useDefaultPath: false });
After that, you can simply change the url which should be called the way you provided in your question, e.g.:
$.connection.hub.url = "/NrsService/api/TestSignal";
If you also want to change this Url dynamically, you can use the document.location properties. In my case, I did something like this:
var subPath = document.location.pathname.substr(0, document.location.pathname.lastIndexOf("/"));
$.connection.hub.url = subPath; // subpath equals to "/NrsService/api"
Hope this helps.

location.path() not redirecting to page

In node this is how I define my details route (render as jade and send).
app.get('/details', function(req, res){
jade.renderFile('details.jade', function(err, html){
if(err){
console.log(err);
}
res.send(html);
});
});
In jade with 'blah' is clicked then calls navigateToPath function with params.
a(ng-click="navigateToPath(date_obj_key, part)") blah
In angular, this function should go to this path. The url path changes in the browser but it does not REDIRECT to the page. Help (yes I am injecting the location service)
$scope.navigateToPath = function(date, part){
var path = '/details?date='+date+'&part_type='+part;
$location.path('/details').replace(); //also tried $location.url(path)
$scope.apply(); //also tried $scope.$apply and $rootScope.$apply as func
console.log($location.path());
}
I am using Fire Fox developer tools(F12) and put a break point on where I used $window.location in my project and looked at the values in $window.location and this what it shows:
It seems like this would work. for both a location in the same folder or sub-folder as well as going to a completely different web site.
$window.location = $window.location.origin + path
or
$window.location = <whatever website you want to go to>
In my case I was just using the $window.location to call a rest service to download a file that the user selected from a ui-grid while still staying on the same page. and this may have worked for me because my scenario is a bit different then what yours is I think. so all I had to do was
$window.location = "../../services" + "<path to my rest service>" + $scope.shortCode + "/" + $scope.wireInstSelectedRow.entity.fileName;
#shapiro I am not sure why this does not work
$location.path('/details').replace();
I tried the same thing originally in my project and based on the documentation: https://docs.angularjs.org/api/ng/service/$location It seems like that would work and what its supposed to be used for but what I noticed is it would put a '#' character in the url before it put the path I wanted it to take which was preventing it from going to that page. Anyhow for me it seems like as long as you are going to an html page that is in the same folder or sub-folder just doing
$window.location = <the path you want to go to>;
is a good solution... at least it did the trick for me. Hope this helps.

Dynamic content Single Page Application SEO

I am new to SEO and just want to get the idea about how it works for Single Page Application with dynamic content.
In my case, I have a single page application (powered by AngularJS, using router to show different state) that provides some location-based search functionalities, similar to Zillow, Redfin, or Yelp. On mt site, user can type in a location name, and the site will return some results based on the location.
I am trying to figure out a way to make it work well with Google. For example, if I type in "Apartment San Francisco" in Google, the results will be:
And when user click on these links, the sites will display the correct result. I am thinking about having similar SEO like these for my site.
The question is, the page content is purely depending on user's query. User can search by city name, state name, zip code, etc, to show different results, and it's not possible to put them all into sitemap. How google can crawl the content for these kind of dynamic page results?
I don't have experience with SEO and not sure how to do it for my site. Please share some experience or pointers to help me get started. Thanks a lot!
===========
Follow up question:
I saw Googlebot can now run Javascript. I want to understand a bit more of this. When a specific url of my SPA app is opened, it will do some network query (XHR request) for a few seconds and then the page content will be displayed. In this case, will GoogleBot wait for the http response?
I saw some tutorial says we need to prepare static html specifically for Search Engines. If I only want to deal with Google, does it mean I don't have to serve static html anymore because Google can run Javascript?
Thanks again.
If a search engine should come across your JavaScript application then we have the permission to redirect the search engine to another URL that serves the fully rendered version of the page.
For this job
You can either use this tool by Thomas Davis available on github
SEOSERVER
Or
you can use the code below which does the same job as above this code is also available here
Implementation using Phantom.js
We can setup a node.js server that given a URL, it will fully render the page content. Then we will redirect bots to this server to retrieve the correct content.
We will need to install node.js and phantom.js onto a box. Then start up this server below. There are two files, one which is the web server and the other is a phantomjs script that renders the page.
// web.js
// Express is our web server that can handle request
var express = require('express');
var app = express();
var getContent = function(url, callback) {
var content = '';
// Here we spawn a phantom.js process, the first element of the
// array is our phantomjs script and the second element is our url
var phantom = require('child_process').spawn('phantomjs',['phantom-server.js', url]);
phantom.stdout.setEncoding('utf8');
// Our phantom.js script is simply logging the output and
// we access it here through stdout
phantom.stdout.on('data', function(data) {
content += data.toString();
});
phantom.on('exit', function(code) {
if (code !== 0) {
console.log('We have an error');
} else {
// once our phantom.js script exits, let's call out call back
// which outputs the contents to the page
callback(content);
}
});
};
var respond = function (req, res) {
// Because we use [P] in htaccess we have access to this header
url = 'http://' + req.headers['x-forwarded-host'] + req.params[0];
getContent(url, function (content) {
res.send(content);
});
}
app.get(/(.*)/, respond);
app.listen(3000);
The script below is phantom-server.js and will be in charge of fully rendering the content. We don't return the content until the page is fully rendered. We hook into the resources listener to do this.
var page = require('webpage').create();
var system = require('system');
var lastReceived = new Date().getTime();
var requestCount = 0;
var responseCount = 0;
var requestIds = [];
var startTime = new Date().getTime();
page.onResourceReceived = function (response) {
if(requestIds.indexOf(response.id) !== -1) {
lastReceived = new Date().getTime();
responseCount++;
requestIds[requestIds.indexOf(response.id)] = null;
}
};
page.onResourceRequested = function (request) {
if(requestIds.indexOf(request.id) === -1) {
requestIds.push(request.id);
requestCount++;
}
};
// Open the page
page.open(system.args[1], function () {});
var checkComplete = function () {
// We don't allow it to take longer than 5 seconds but
// don't return until all requests are finished
if((new Date().getTime() - lastReceived > 300 && requestCount === responseCount) || new Date().getTime() - startTime > 5000) {
clearInterval(checkCompleteInterval);
console.log(page.content);
phantom.exit();
}
}
// Let us check to see if the page is finished rendering
var checkCompleteInterval = setInterval(checkComplete, 1);
Once we have this server up and running we just redirect bots to the server in our client's web server configuration.
Redirecting bots
If you are using apache we can edit out .htaccess such that Google requests are proxied to our middle man phantom.js server.
RewriteEngine on
RewriteCond %{QUERY_STRING} ^_escaped_fragment_=(.*)$
RewriteRule (.*) http://webserver:3000/%1? [P]
We could also include other RewriteCond, such as user agent to redirect other search engines we wish to be indexed on.
Though Google won't use _escaped_fragment_ unless we tell it to by either including a meta tag; <meta name="fragment" content="!">or using #! URLs in our links.
You will most likely have to use both.
This has been tested with Google Webmasters fetch tool. Make sure you include #! on your URLs when using the fetch tool.

angular changing the url location without reloading the page

I have some partials which are loaded with some URL templates/test.html for example. This TemplateURL will always be relative. I want to use the same templates in different locations within the website.
So , I want to use the same relative url http://somedomain.com/templates/Test.html even if I am on some actual url of http://somedaomian.com/some1/some2
I have tried to use the $loaction service, but I am unable to set the $loaction back to the home url when I need to.
E.g in my controller I would like to :
var new_base_url = homeURL();
function homeUrl() {
/* Here is where I am unable to get the home url */
$location.path('/'); // simply returns the current url
};
If you want the absolute Url, $location.absUrl() will return everything (all url segments).
If you want the host name, $location.host() will return the host name.
If you want the protocol, $location.protocol() will return that.
If you want the path, $location.path() will return that.
If you want the hash, $location.hash() will return that.
You should be able to use these methods to parse out the pieces of the url that you are after.
var path = $location.path();
var hash = $location.hash();
var basePath = path.replace(hash, '');

Whats the better way to identify the context path in Angular JS

I have my web application deployed to tomcat with an applicatio context.
For example my URL looks something like this.
http://localhost:8080/myapp
myapp - is the application context here.
Now in an Angular service if i want to call a webservice say getusers. My URL should be this /myapp/getusers. But I want to avoid hardcoding the application context as it might change from one deployment to other.
I have managed to figureout the contextpath from $window.location.pathname but it looks very stupid. Is there a betterway?
FYI I am using Spring MVC for restful services.
What I have done is declared a variable in the main jsp file. Then that variable will be available throughout the angular application.
<script type="text/javascript">
var _contextPath = "${pageContext.request.contextPath}";
</script>
This code should be written in header before including other JavaScript libraries.
I'm also using tomcat and Spring MVC. Using relative url in JavaScript will do the trick.
For doing this you just need to remove the / at the begining of REST url. so that your url starts from the current url in your browser.
replace $resource('/getusers') with $resource('getusers')
Inject the $location service to your controller.
var path = $location.path(); // will tell you the current path
path = path.substr(1).split('/'); // you still have to split to get the application context
// path() is also a setter
$location.path(path[0] + '/getusers');
// $location.path() === '/myapp/getusers'
// ------------------ \\
// Shorter way
$location.path($location.path() + '/getusers');
// $location.path() === '/myapp/getusers'
In Angular 2 (if using hashbang mode). Below code can be used to form the url.
document.location.href.substr(0, document.location.href.lastIndexOf("/#")) + "/getusers";
Inspired from the answer of #jarek-krochmalski
if you are using hashbang mode, with "#", you can do something like that:
$location.absUrl().substr(0, $location.absUrl().lastIndexOf("#")) + "/getusers"
For AngularJS $http service you are good to go with url : 'getusers', as follows:
$scope.postCall = function(obj) {
$http({
method : 'POST',
url : 'getusers',
dataType : 'json',
headers : {
'Content-Type' : 'application/json'
},
data : obj,
});
};
In general, you should use injection in your controller like the following:
angular.module("yourModule").controller("yourController", ["$scope", "yourService", "$location", function($scope, yourService, $location){
....
//here you can send the path value to your model.
yourService.setPath($location.path());
....
}]);

Resources