getting data from a scrape on load - javascript

I am new to software development and am trying to build a fullstack javascript app on my own.
I currently am running a scrape with cheerio in express, as follows:
app.get('/scrape', function(req, res){
//do things.
})
I will be using Angular for the front end.
How do I do the scrape whenever a user visits my home page/root route, so that I have data to compare against their inputs in angular? assume that the home page is at '/'.
this is what my angular app.js looks like so far:
angular.module('FFTrades', [
'FFTrades.services',
'ngRoute'
]).config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl: 'app/tradeanalyzer/tradeanalyzer.html',
controller: 'TradesController'
})
})

app.run will help you to check your url
app.run(function ($rootScope, $cookies, $location, $http) {
$rootScope.$on('$routeChangeStart', function (event, next, current) {
if (next.originalPath != '/') {
console.log('inside your home page');
}
});
});

You would want to use a .run module. These are run automatically when your app starts up.
And add your scrap data to a service or the $rootScope.
app.run(function($rootScope) {
$rootScope.hello = function() {
console.log('hello');
}
});
If you are new to angular you might run into some issues getting the result from the scrape promise and applying it to the $scope. These would be new questions, but above should answer the particular question you are looking for.

Related

Programmatically add ngRoute to AngularJS webpage

I am trying to create a Chrome extension for my school's Online Learning Platform. This website uses HashLocationStrategy, with multiple 'pages'.
I want to add custom ngRoutes to the page, so whenever it goes to the following URL: ".../magister/#/plus" it load my custom template into the ng-view component. I have tried the following script:
angular.module("MagisterPlusRouting", ["ngRoute"])
.controller("RootController", ($scope, $route, $routeParams, $location) => {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
})
.controller("PageController", ($scope, $routeParams) => {
})
.config(($routeProvider, $locationProvider) => {
$routeProvider.when("/plus", {
templateUrl: "index.html",
controller: "PageController",
});
$locationProvider.html5Mode(true);
});
But that does not seem to work, I get the following message in my console routechange undefined 0, this originates from the website's official script.
Is it even possible to do this? How do I add these new routes? If you need further information, tell me. Although I do not have access to the development source code of the website.

Several angular modules for routing

Can i create several modules for routing in AngularJS app like:
1. First route management file:
angular.module('app.p.routes', ['ngRoute'])
.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/forbidden',
{
templateUrl: 'app/views/pages/forbidden.html'
})
.......................
2. Second route management file:
angular.module('app.admin.routes', ['ngRoute'])
.config(function ($routeProvider) {
$routeProvider
.when('/admin-dashboard',
{
templateUrl: 'app/views/pages/admin/dashboard.html',
controller: 'dashboardController',
controllerAs: 'dashboard'
})
.............................
3. Main app file:
angular.module('mainApp',
[
'ngAnimate', //animating
'app.p.routes', //public routing
'app.admin.routes',
'ui.bootstrap',
'ngParallax', //parallax effect
'ngFileUpload'
])
When i tried to use this approach page hangs and angular throws error:
> VM188:30554 WARNING: Tried to load angular more than once.
I need an approach to split public and admin routing management.
You can have as many AngularJS modules as you like. There are no rules against that, however, you've attempted to include the Angular source twice which is why you're seeing this warning...
> VM188:30554 WARNING: Tried to load angular more than once.
The simplest solution to your issue that I can think of, is to add an event listener to the $routeChangeStart event. With this you'll be able to verify that the current user has the correct permissions to view anything before they actually to do so.
A simple Service to store some basic information on the current user could like this.
var app = angular.module('app', ['ngRoute']);
app.service('AuthenticationService', function () {
// Set the User object
this.setUser = function () {
this.$user = user;
};
// Get the User object
this.getUser = function (user) {
return this.$user
};
});
And then upon receiving the $routeChangeStart event, you can retrieve the user object and confirm that they are allowed to proceed to the chosen resource.
Here's an example, whereupon a user needs to be an Administrator to view any route that has "/admin" in it.
app.run(function ($rootScope, $location, AuthenticationService) {
// Create a listener for the "$routeChangeStart" event
$rootScope.$on('$routeChangeStart', function () {
// Is the user is an Administrator? Are they attempting to access a restricted route?
if ($location.url().indexOf('/admin') && !AuthenticationService.getUser().isAdmin) {
// Redirect the user to the login page
$location.path('/login');
}
});
});
If you want a more advanced solution however, have a look at this: https://github.com/Narzerus/angular-permission
This will enable you to achieve a more in-depth ACL implementation across your application.

How to handle page reload in angularjs app for url that doesnt exist in laravel

How to handle page reload in AngularJS app for URL that doesn't exist in Laravel routes
I don't know how to bump but I have the exact same problem as this guy and looks like his question didn't get answered.
I'm using angular 1.4.8 and laravel 5.2.
If I load the page "home.php" it works(shows home content and "main" content).
I press a link to open home/info and it works and I see the info page loaded with angular routes.
Now if I refresh this I get an error(Not found exception).
How can I fix this in laravel?
My angular routes for home.php:
app.config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true).hashPrefix('!');
$routeProvider
.when('/', {
templateUrl : '/main'
})
.when('/info', {
templateUrl : '/info'
});
});`
Laravel routes:
Route::get('home', function () {
return view('home');
});
Route::get('main', function () {
return view('main');
});
Route::get('info', function () {
return view('info');
});
So what's not working: I can't go directly to home/info(or refresh it). I can only go to home, then press link to home/info to see it. It should load home page with info page loaded(with angular routes).

Routing to non-Angular pages within Angular

I am converting a large server rendered app to use Angular. Because of the size, we are doing it a bit at a time. During this conversion period, part of the app will use Angular and part will not. This means that routing sometimes will route within the Angular app and sometimes it will need to transition from old world to new world (easy) or new world to old world (harder).
Ideally, I would like to specifically route some page transitions within the Angular app (new world) to the proper controllers but then any other page transitions should just fetch new HTML pages (old world).
I can't seem to figure out how to do this. I think I need to use the routeProvider and when / otherwise, but there isn't a lot of documentation that I found which is helpful.
You can't use routeProvider for the old world, since angular routes only direct you within the actual same page.
You could make a placeholder angular route for each legacy route, then in the controller, inject $window and do something like:
$window.location.href = destinationUrl;
Something like: (go to the old world on logout)
app.controller('LogoutCtrl', function ($scope, $window) {
var destinationUrl = 'https://mywebsite.com/';
$window.location.href = destinationUrl;
});
Vice versa, to go back to the angular world, just use a normal link to your angular route:
Link
If you want a catch-all route to redirect to the outside, you can do the following:
otherwise({
controller: 'NotFoundCtrl'
});
...
app.controller('NotFoundCtrl', function($scope, $location, $window) {
var path = $location.path();
$window.location.href="http://test.com" + path;
})
As triggerNZ said, you can always have a controller redirect unhandled routes to the outside. Here is the HTML and Javascript showing how to do it.
HTML
<div ng-app="myApp">
<script type="text/ng-template" id="this.html">
This Page.
</script>
<script type="text/ng-template" id="that.html">
That Page.
</script>
<div>
<ul>
<li>This</li>
<li>That</li>
<li>Other</li>
</ul>
<ng-view></ng-view>
</div>
</div>
Javascript
var app = angular.module("myApp", ['ngRoute']);
app.config(function ($routeProvider, $locationProvider) {
$routeProvider.when('/this', {
templateUrl: 'this.html'
}).when('/that', {
templateUrl: 'that.html'
}).otherwise({
template: "<div></div>",
controller: function ($window, $location, $rootScope) {
if (!$rootScope.isInitialLoad) {
$window.location.href = $location.absUrl();
}
}
});
$locationProvider.html5Mode(true);
});
app.run(function ($rootScope) {
$rootScope.$on('$routeChangeSuccess', function() {
$rootScope.isInitialLoad = (typeof $rootScope.isInitialLoad === "undefined");
});
});

Angular ui-router with express

I have set up ui router with the following states:
$locationProvider.html5Mode(true);
$urlRouterProvider.otherwise('/');
$stateProvider
.state('adminprojects', {
url: '/adminprojects',
templateUrl: 'views/adminProjects.html',
controller: 'adminProjectsCtrl'
})
.state('adminprojectsdetails', {
url: '/adminprojects/:id',
templateUrl: 'views/adminProjectsDetails.html',
controller: 'adminProjectsDetailsCtrl'
})
adminprojects view contains a list with ui-sref links. eg
<li><a ui-sref="adminprojectsdetails({id: project.id})" href="/adminprojects/1">Project 1</a></li>
If I click this link for example adminprojects/1 the adminProjectsDetails.html view is shown correctly. However if I refresh this page or navigate directly to this url then the view does not load.
This however works as expected if I have html5 mode set to false;
In express I have this
router.get('/*', function(req, res) {
res.sendfile(__dirname + '/public/index.html');
});
Controller are just pretty much boilerplate for now:
angular.module('jhApp')
.controller('adminProjectsCtrl', function($scope, projects) {
$scope.projects = projects.items;
});
and
angular.module('jhApp')
.controller('adminProjectsDetailsCtrl', function($scope, $stateParams) {
console.log($stateParams);
});
Any ideas why this is not working?
Did you create your project generator-angular ?
If so put <base href="/"/> inside your HEAD above all other elements.
Generator angular create index.html using relative paths for src folders like :
<script src="xxx/yyy.js"/>
When you refresh the page , browser looking for /adminprojects/xxx/yyy.js (.css , *) file which is not found. Because of that you can get lots of script and style errors. Using base tag fixes that problem.
Or simply just change your all src locations to "xxx/yyy." -> src="/xxx/yyy."

Categories