AngularJS - Error: [$compile:tpload] Failed to load template (Spring Boot) - javascript

I've checked similar questions online for this, but none of them satisfied my issue. I'm building a simple SPA with angularjs 1.6.4 and spring boot.
Error: Error: [$compile:tpload] Failed to load template: test.html
(HTTP status: 404 )
It is working fine when I don't add ngRoute to the code & it fails to load the html template when I try to run it with routes. My backend is springboot with thymeleaf template (not sure if this is causing issue of some sort) because running the UI code alone in xampp server provides the routing correctly.
I initially thought in the templateUrl I've mentioned the wrong path. Here is how my folder structure looks.
To reduce strain I've added my entire JS code in single index.html as a tag here.
<!DOCTYPE HTML>
<html>
<head>
<title>test</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
</head>
<body ng-app="app">
<ng-view></ng-view>
<script>
// Creating Routes (ngRoute)
var app = angular.module('app', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider.when("/", {
templateUrl : 'test.html',
controller : 'postcontroller'
}).when("/uploadPath", {
templateUrl : 'test1.html',
controller : 'uploadPath'
}).otherwise({
redirectTo : "/"
});
});
// Creating controller
app.controller("uploadPath", function($scope, $location) {
$scope.passthrough = function() {
$location.path('/uploadPath')
};
});
app.controller('postcontroller', function($scope, $http, $location) {
// be used to decide for showing PostResults
$scope.postDivAvailable = false;
// be used for decide for showing GetResults
$scope.getDivAvailable = false;
$scope.submitForm = function() {
// post URL
var url = $location.absUrl() + "api/config/save";
// prepare headers for posting
var config = {
headers : {
'Content-Type' : 'application/json',
'Accept' : 'application/json'
}
}
// prepare data for post messages
var data = {
xx: $scope.xx,
yyyy: $scope.yyyy,
zzzz: $scope.zzzzz
};
// do posting
$http.post(url, data, config).then(function(response) {
$scope.postDivAvailable = true;
$scope.postCust = response.data;
}, function error(response) {
$scope.postResultMessage = "Error Status: " + response.statusText;
});
// reset data of form after posting
$scope.xx= '';
$scope.yyyy= '';
$scope.zzzzz= '';
}
});
</script>
</body>
</html>
In the test.html file I just have a form with three fields. The problem here is that when I load localhost:8080/ the test.html itself is not loading & it throws this error.
Error: [$compile:tpload] Failed to load template: test.html (HTTP status: 404 )
any help is much appreciated!!

This is the fix I did which solved the problem. I'm not sure If Im understanding is correct on this question. So kindly improve this answer if someone has better understanding on the problem.
Basically the Spring Boot Thymeleaf templating engine takes the .html file from the src/main/java folder structure. But when the routes are added, the Spring Boot application expects all the .html files to be inside the webapp folder. i.e src/main/webapp.
After placing the .html files inside the webapp folder solved the issue. There were no issues in the angularJS routing codes.

Related

AngularJs does not read url

I need to use angularJS to call a rest api located at localhost:80/users.
The problem is that it does not read the url (the url works if I access it in the browser).
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>Today's welcome message is:</p>
<h1>{{myWelcome}}</h1>
</div>
<p>The $http service requests a page on the server, and the response is set as the value of the "myWelcome" variable.</p>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("https://www.w3schools.com/angular/welcome.htm").then(function (response) {
$scope.myWelcome = response.data;
});
});
</script>
</body>
</html>
When I run the code from above (which is from https://www.w3schools.com/angular/tryit.asp?filename=try_ng_services_http) on my PC I don't see the correct result. Instead
Today's welcome message is:
Hello AngularJS Students
The $http service requests a page on the
server, and the response is set as the value of the "myWelcome"
variable.
I see
Today's welcome message is:
The $http service requests a page on the server, and the response is
set as the value of the "myWelcome" variable.
in Chrome and Firefox.
If I replace the url from the code (https://www.w3schools.com/angular/welcome.htm) with my localhost/users, I also don't see the correct result. But, if the url is https://restcountries.eu/rest/v1/region/europe it works! Why does it work for some URLs and it does not for others?
The server which is running the angularJs uses a different localhost port than the Rest server provider. Could this be the problem?
I use the latest AngularJS version (1.6.7).

Can one server serve 2 angularjs modules / routings?

(I re-edited my initial question to better explain the context.)
I have a mean-stack web site built with angular-ui-router and html5mode. routes/index.js contains the following code, and it is views/index.html which has <ui-view></ui-view> and is the entry point of all the pages. As a result, https://localhost:3000/XXXX in a browser will remain the same (rather than adding #) and show the corresponding content based on the router.
router.get('*', function(req, res) {
console.log("router.get *");
res.sendfile('./views/index.html');
});
Now, because of this problem, I want to have views/addin.html that contains office.js and another router, such that the site serves a set of urls https://localhost:3000/addin/XXXX, and I don't mind if it is html5mode or not (a url can contain # somewhere). To this end, I added one block for addin in routes/index.js:
router.get('/addin/*', function (req, res) {
console.log("router.get /addin/*");
res.sendfile('./views/addin.html')
});
router.get('*', function(req, res) {
console.log("router.get *");
res.sendfile('./views/index.html');
});
And here is views/addin.html:
<html>
<head>
<title>addinF</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.2/angular-ui-router.js"></script>
</head>
<body ng-app="addinF">
addin content
<ui-view ng-cloak></ui-view>
</body>
<script>
var addinApp = angular.module('addinF', ['ui.router'])
addinApp.config(['$stateProvider', function ($stateProvider) {
$stateProvider
.state('addinNew', {
url: '/addin/new',
template: "new page"
})
.state('addinHome', {
url: '/addin/home',
template: "home page"
})
}]);
</script>
</html>
However, loading https://localhost:3000/addin/new or https://localhost:3000/addin/home just shows addin content and does not show new page or home page in console; it did not raise any error either.
Could anyone tell me what's missing? Can one server serve 2 angularjs modules or routings?
Just add initial redirection:
appAddin.config(['$urlRouterProvider', function ($urlRouterProvider) {
$urlRouterProvider.otherwise("/addin/new");
}])
There is a working plunker

podio API JS browser authentication and API calls

I'm quite newbee on API thing, been reading the documentation here for JAVASCRIPT client but I can't make things work, even on authentication part. I already have the client ID and ClientSecret from PODIO itself.
Basically, I want to get all podio data in a workspace in a JSON format using client side (browser only).
I've downloaded the library here and created an HTML file on my localhost and link the podio-js with following code. Getting this error "podio-js.js:1 Uncaught ReferenceError: require is not defined at podio-js.js:1". Do I need to install something such that loader thing to make this work?
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript" src="lib/podio-js.js"></script>
<script type="text/javascript">
var podio = new PodioJS({
authType: 'server',
clientId: 'foo',
clientSecret: 'foo'
});
var redirectURL = 'http://localhost/PODIO-JS/podio-js-master/PODIO_CLIENT.html';
// Your request handler (for example in ExpressJS)
var action = function(request, response) {
var authCode = request.query.code;
var errorCode = request.query.error;
podio.isAuthenticated().then(function() {
// Ready to make API calls...
}).catch(function(err) {
if (typeof authCode !== 'undefined') {
podio.getAccessToken(authCode, redirectURL, function(err, response) {
// make API calls here
console.log (responsedata);
});
} else if (typeof errorCode !== 'undefined') {
// a problem occured
console.log(request.query.error_description);
} else {
// start authentication via link or redirect
console.log(podio.getAuthorizationURL(redirectURL));
}
});
</script>
</head>
<body>
</body>
</html>
You can only use the syntax PodioJS = require('podio-js') if you're working in an AMD environment, typically using requirejs.
You're using a good ol' HTML page instead, which means you have to follow the second part of the browser usage section found here: https://github.com/podio/podio-js#browser
From within the podio-js folder:
npm install -g browserify
npm run bundle
and then include dist/podio-js.js using a tag in your HTML page.
Note: once you've bundled the source, you can copy paste the compiled file wherever you want.

Angular-ui nested views in HTML5 mode get 404 not fount for template file

I have a problem with my app in HTML5 mode and nested URL, let me explain.
This is an example routing file:
angular.module('widgets').config(['$stateProvider',
function($stateProvider) {
$stateProvider.
state('widgets', {
url: '/widgets',
abstract: true
}).
state('widgets.create', {
url: '/create',
views: {
'content#': {
templateUrl: 'modules/widgets/views/widgets.create.client.view.html',
}
}
});
}
]);
This works until I keep HTML5 mode off with:
$locationProvider.hashPrefix('!');
As I turn on the HTML5 mode with:
$locationProvider.html5Mode(true).hashPrefix('!');
It happens that as soon as I try the nested URL /widgets/create I get 404 error not found for the templateUrl file because it prefix it with /widgets/so instead getting this:
http://127.0.0.1/modules/widgets/views/widgets.create.client.view.html <-- 200 OK HTML5 OFF
It instead try to get:
http://127.0.0.1/widgets/modules/widgets/views/widgets.create.client.view.html <-- 404 Not Found HTML5 ON
Any ideas?
I found it! When you enable HTML5mode you need to add this tag in the head of your main document:
<head>
<base href="/" />
...
</head>
Here is the explanation: https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#issue-my-assets-and-templates-are-not-loading

How get data with angular from the backend and send it with node.js for the frontend?

I'm changing my node.js application, i was using EJS template engine and now i want use angular.
For this i already install angular and is working good, but now i want get my data, and for this i'm using the $http service:
(function($) {
app.controller('EventCtrl', ['$scope', '$http', function($scope, $http){
$scope.data;
$http.get('/data').
success(function(data, status, headers, config) {
$scope.data = data;
}).
error(function(data, status, headers, config) {
$scope.data = data;
});
}]);
}(jQuery));
And i'm sending the data in the backend:
restAPI.GET(options).then(function (result) {
res.render('data/index.html', {
event: result,
});
}).then(undefined, function (error) {
console.log(error);
});
But its returning the HTML from the same page that i'm using the controller. What am i doing wrong here??
What is returning:
<!DOCTYPE html> <html ng-app="app"> <head> <title> Testando Angular </title> </head> <body> <div ng-controller="EventCtrl"> {{data}} </div> </body> <script type="text/javascript" src="/lib/jquery/dist/jquery.min.js"></script> <script type="text/javascript" src="/lib/angular/angular.min.js"></script> <script type="text/javascript" src="/app.js"></script> <script type="text/javascript" src="/controllers/EventCtrl.js"></script> </html>
You need to have node serve up the page which angular lives on.
(This is using just an example using express)
Something like this:
app.get('/', function(req, res) {
res.sendFile('../public/index.html');
res.end();
});
Then you need to set up routes for angular to query so it can get data:
app.get('/api/data', function (req, res) {
//Get some data here however you do that
res.json(data) //Send your data back to angular in the callback of your database query ( or whatever you are doing )
}
You use res.render() to send a page. You don't want to send a page. You just want to send data if you are using the $http.get request shown above. Fetch your data and send it with res.json(data)
If you need some insight into how all the pieces fit together, I would recommend working through the following tutorial:
Setting Up a MEAN Stack SPA

Categories

Resources