简体   繁体   中英

How Angular application work when I enter URL directly in browser?

I know Angular work by something called Single-Page-Application.
But what puzzled me is that when I enter URL directly in the browser. It can still find the correctly page.

For example. When I enter http://localhost/ , I know it is going to the display index.html
But when I enter http://localhost/asd , It can still work, but the build result didn't contain asd .
How??? Dear SO community.

I will try to explain.

  1. Server starts by serving the index.html.

  2. If you check contents of the index.html you will find

app-root or a similar selector that will decide which component will be loaded.

  1. app-root is the selector of app.component.ts

Meaning it will display app.component by default.

  1. Note that this is the default case. http://localhost/asd and others all default to this.

You can see how to default to a diffent component by default on this stackblitz.

https://stackblitz.com/edit/my-angular-starter-g2kuyy?file=index.html

Note: If you want to have different sets of navigation, you can achieve that by routing.

The server is probably configured to respond with the HTML document that bootstraps the Angular application for any URL that would normally throw a 404 error.

How?

In any case if you access an url like http://my-url.com or http://localhost/ and you pass whatever after the / it will work unless you made a redirection to 404 page or wherever you'd like.

Why?

Because your url is correct, and doesn't handle what you pass as a parameter of your url, unless you make it handle it.

As it turn out I config my go server to direct all 404 page to the index.html so that when I input http://localhost/asd in navigation bar, it direct to index.html , and /asd is then processed by single page application of angular with windows.location.url

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM