Angular: URL change doesn't reload page first

2020-03-29 05:19发布

问题:

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 data for different products. The products names are shown in the URL

The site works fine from links in the site to the different products.

If I update the URL directly with the product name and press enter and site does not reload. I have to select the whoile URL and press enter again for the page to reload.

Can anyone think why this might be happening?

回答1:

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.



标签: angular