There is an already written web application, I want to rewrite the entire front on an angular. I decided to use Angular 2 in order to practice now and when the stable version is released to have some kind of development experience on it. The first thing I encountered is routing, when we go to the application http://mybestapp.com/ index.html page loads, which loads the anngular itself. When we go somewhere from the main page, for example, click on the /getUser/123 link, the server gives json and we draw the data in the browser. But, if we immediately follow the link http://mybestapp.com/getUser/123 in a new window, we will get just a json string (this is normal server behavior in response to such a get request). Of the ways to get out of this situation, I have come up with only one yet - to look in the getUser controller on the server (and in general in all controllers) whether the x-requested-with:XMLHttpRequest header was transmitted, and if not, then redirect the user to the main page ( http://mybestapp.com/ ), or rather not even redirect, but simply, stupidly take and give him the content of the main page, but at the same time stay on /getUser/123 . But if x-requested-with was submitted, then we will give json. Here you should also note that there are all sorts of pages 404 and other errors.

Please tell me if my approach is correct (it seems to me that there is not), and how to solve this problem correctly?

  • But is it not better in this case to separate the front and back separately? In order to give backend only by api json , then the front routing will work normally without any additional games with header viewing. - Moonvvell
  • @Moonvvell, describe briefly how it should look. What behavior will be in the case of this example that I described, namely, a direct link to the link http://mybestapp.com/getUser/123 - sanu0074
  • 2
    If there is a normal API for example, do it the address api.mybestapp.com/getUser/123 or mybestapp.com/api/getUser/123 . It will be two independent applications - api sends the data, and the angular application accepts data from the api, and already goes through its routing, the routing of the angular will in no way be in contact with the backend routing. - Moonvvell pm

2 answers 2

If you divide your application into backend and frontend, then you should redirect all requests to the server (to the pages) to index.html, and routing angular will resolve itself. In the angular services you access the api server, which already gives the data.

  • That's what I said in the question, but I was not sure that it was right - sanu0074

You can make it easier, add to the import of the router in the main useHash module: true RouterModule.forRoot(ROUTES, { useHash: true }) in this case, all URLs will be http://mybestapp.com/#/getUser/123 and no additional dances with a tambourine around the server is not needed