Angular: URL change doesn't reload page first time

后端 未结 1 1467
闹比i
闹比i 2021-01-15 01:24

I know this is a bad question, and I have no code but I was hoping someone can possible shed some light on this.

I have an Angular site.

The site loads sales

1条回答
  •  野的像风
    2021-01-15 02:19

    You need a way to tell the server that the URLs you are entering are valid Angular routes. And hence you need to map these URLs to index.html.

    Since I use Java/Spring at the back-end. Here is how I do it. This solves the problem:

    @Controller
    public class Routing {
    
        @RequestMapping({"/resources/**"}) 
        public String api(final HttpServletRequest request){
            String path = (String) request.getAttribute(
                    HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
            return path;
        }
    
        @RequestMapping({ "", "/login", "/products/**" })
        public String gui() {
            return "forward:/index.html";
        }
    }
    

    Here the first method just returns the paths that starts with "/resources/**", because under this path, all my REST APIs are available. The second method forwards to index.html for the Angular routes.

    Note that forwarding to index.html does not change the URL on the browser address bar, but it triggers Angular to take control.

    0 讨论(0)
提交回复
热议问题