Having difficulty navigating between Spring MVC and Angular Js components in my project

https://i.sstatic.net/Iovci.png

I am currently facing an issue with my project structure. I received a "Failed to load resource: the server responded with a status of 404 ()" error message, indicating that ShowDetail.jsp is not found. Can anyone advise on the correct path to give in the Route templateURL?

https://i.sstatic.net/Iovci.png

My objective is to populate details on another page when a name is clicked.

I am utilizing Server side (Spring MVC) Service to retrieve the required details.

Below is a snippet of my client-side code:

var App = angular.module("myApp", ['ngRoute', 'angularUtils.directives.dirPagination']);
App.config(['$routeProvider',
  function($routeProvider, $locationProvider) {
    $routeProvider.
    when('/detail/:username', {
      templateUrl: 'showDetail.jsp',
      controller: 'detailController'
    });
  }
]);
angular.module('myApp').controller("myController", function($scope, $http) {
  function getDetails(name) {

    $http.get(REST_SERVICE_URI + '/detail/' + name)
      .then(
        function(response) {

          self.detail = response.data;


        },
        function(errResponse) {
          console.error('Error while fetching Users');

        }
      );

  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
 <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.min.js"></script>
<div ng-controller="myController as ctrl">
  <tbody>
    <tr dir-paginate="u in ctrl.users|orderBy:sortKey:reverse|filter:search|itemsPerPage:5">
      <td><span ng-bind="u.id"></span>
      </td>
      <td>
      <a>
         <span ng-bind="u.name"  ng-click="ctrl.getDetails(u.name)"></span>
      </a>
      </td>
      <td><span ng-bind="u.department"></span>
      </td>
      <td>
      <span ng-bind="u.job"></span>
      </td>
    </tr>
  </tbody>
</div>

IndexController.java

@RequestMapping(value= "/detail/{name}",method = RequestMethod.GET)
 public String getDetails(@PathVariable("name") String name) {
   return "showDetail";
 }

MainController.java

@RequestMapping(value = "/detail/{name}", method = RequestMethod.GET,   produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Detail> getDetails(@PathVariable("name") String name) {
    System.out.println("Fetching detail with name " + name);
    Detail detail = userService.findByName(name);
    if (detail == null) {
        System.out.println("Detail with id " + name + " not found");
        return new ResponseEntity<Detail>(HttpStatus.NOT_FOUND);
    }
    return new ResponseEntity<Detail>(detail, HttpStatus.OK);
}

ServiceImpl.java

public Detail findByName(String name) {
    for(Detail deatil : details){
        if(deatil.getFirstname().equalsIgnoreCase(name)){
            return deatil;
        }
    }
    return null;
}

I have successfully fetched the details and am able to access them in the AngularJS controller. However, when I click on a name field in the table, the corresponding details should be displayed on another page. Although I can retrieve the required details, the page is not changing. I suspect the issue lies with routing in AngularJS and Spring MVC. I would appreciate any assistance on how to resolve this problem.

Answer №1


To navigate to a different page, you can utilize the $location service in AngularJS. Depending on your route configuration, the code snippet might resemble the following:

function (response) {

    self.detail= response.data;

    //Include the following two lines
    var username = response.data.username;
    $location.path('/detail/' + username);

},

Important: Don't forget to inject $location into your controller:

angular.module('myApp').controller("myController", function($scope, $http, $location) {
    ...
});

Answer №2

Make sure to include $window.location.href within the success block of your $http.get function.

$http.get(REST_SERVICE_URI + '/detail/' + name)
      .then(
        function(response) {

          self.detail = response.data;  
          $window.location.href = "#yourCustomUrl";    

        },
        function(errResponse) {
          console.error('Error occurred while retrieving data');

        }
      );

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on displaying dynamic content on a single page with AngularJS 1.6

Just getting started with Angular and looking for a way to display dynamic content from a JSON file using AngularJS 1.6? Here's an example to help you out. News.json { "Articles": [ { "Title": "News 1", ...

You can update a JavaScript string by adding values using the '+=' operator

I have the following function: function generateJSONstringforuncheckedfilters(){ jsonstring = ''; jsonstring = "["; $('body').on('click', 'input', function(){ jsonstring += "[{'OrderGUID&apo ...

What is the best way to switch between search results shown in an li using AngularJS?

Looking for a way to toggle a list that appears when a user searches in my app. I want the search results to hide when the search bar is closed. How can I achieve this? I think Angular might be the solution, but I'm stuck on how to implement it. I tri ...

The getJSON function is showing [object Object] instead of the expected values

Having trouble displaying JSON data in an HTML list? When trying to loop through the JSON file, you might encounter issues such as displaying [object Object]. Check out the script below for assistance: Here is the original JSON: [ { "us":"USA ...

The feature of Access Control Request Headers involves appending certain information to the header of an AJAX request when using jQuery

Looking to enhance an AJAX POST request from jQuery with a custom header. Attempted solution: $.ajax({ type: 'POST', url: url, headers: { "My-First-Header":"first value", "My-Second-Header":"second value" } ...

What is the simplest method for displaying a collection of list items?

Currently, I am working on a project using React JS. I am trying to display a list using a ul element with each item in the array as a separate li. let listItems; let listItem; while (true){ listItem = prompt("Enter a list item or press cancel t ...

Sort with AngularJS: orderBy multiple fields, with just one in reverse

Currently, I am faced with the challenge of filtering data based on two variables: score and name (score first, followed by name). This task involves various games, some of which have scores in reverse order (like golf) while others maintain a normal scor ...

Extract the Date portion from a DateTime object in ASP.NET MVC

I am currently facing an issue with a property in my Model [Display(Name = "День рождения")] [DataType(DataType.Date)] public System.DateTime Birthday { get; set; } When trying to save the value to the database using AJAX, it is also ...

Preparing data before using Kendo UI upload function is essential

I need to pass a data (specifically a GUID) to the upload method of the kendoUpload, so that a particular MVC Controller action method can receive this data each time the upload occurs. $("#propertyAttachmentUpload").kendoUpload({ async: { ...

Every time a new modal is opened, the Bootstrap modal within the code seems to magically multiply itself

Hey there! I recently implemented a room password validation feature for the chat application I developed. To display the password input to users, I utilized Bootstrap's 4 modal. https://i.sstatic.net/4wJQp.png The modal is triggered using jQuery wi ...

Is there a reason to not simply reset the connection to the $.ajax?

Ensure that the server is available before loading the scripts. On the client side jQuery(document).ready(function(){ jQuery.ajax({ dataType: "jsonp", timeout: 1000, cache: false, url: "http://xxx/include/xxx.php?q=? ...

Can diverse array elements be divided into separate arrays based on their object type in JavaScript?

Looking to create new arrays based on objects with similar attributes from an existing array? Here's how: Starting with this [ {name: "test", place: "country"}, {name: "walkAndEat", Long: 100, Lat: 15, Location: "place name"}, {name: "te ...

If a value is located, select a new value from the identical object

Is it achievable to scan through an array of JSON objects? My goal is to locate a particular value within one of the objects and then extract other values from that same object. Is this possible? Appreciate any guidance. Thank you. ...

A convenient way to implement a polyfill for the Object.create method in JavaScript using

A new way to implement the polyfill for javascript Object.create() has left me puzzled. You can find the code here. if (typeof Object.create != 'function') { // Implementation steps based on ECMA-262, Edition 5, 15.2.3.5 // Reference: ...

AngularJS efficiently preloading json file

I am just starting to learn about angularJS. Apologies if my question is not very clear. Here is the problem I am facing: I have a JSON file that is around 20KB in size. When I attempt to load this file using the 'factory' method, I am receivin ...

Incorporating external content to make it easily discoverable by Google for optimal SEO performance

I am currently working on a project that involves loading external content onto a customer's site. Our main goal is to provide the customer with a simple inclusion method, such as a one-line link similar to Doubleclick, without requiring any server-si ...

Using Angular select asynchronously within a custom directive

Despite my efforts, I am struggling to get an angular select with async to work properly. It seems to be mostly working, but not entirely. Consider the controller below: $scope.stuff = {}; $scope.stuff.blah = "SOME_KEY"; External.list().then( function ...

How to retrieve data from a nested object within a JSON array using JavaScript

When I use Logger.log(response.data.phone), the following data is displayed in my log: [{label=work, primary=true, value=5558675309}, {label=work, value=6108287680, primary=false}, {value=6105516373, label=work, primary=false}] My goal is to have the two ...

Changing the text color in a React Native TouchableHighlight component

How does TouchableHighlight change the text color when tapped? I have already configured the backgroundColor using underLayColor. Here is my updated code snippet: <TouchableHighlight style={{ borderRadius: 5}} ...

Understanding the process of verifying signatures with Cloud KMS

I've been struggling to confirm the validity of a signature generated using Google's cloud KMS, as I'm consistently receiving invalid responses. Here's my approach to testing it: const versionName = client.cryptoKeyVersionPath( p ...