英文:
angular routing with urls starting with # doesnt work
问题
我想为Angular 2应用程序创建以#开头的URL路由。但是,Angular会重定向到主页而不是组件页面。我该如何解决这个问题?
我使用了匹配器,但它不起作用。
我为同一个组件使用了两个URL,但它在#上不起作用(URL:customcomponent和#/customcomponent)。我还尝试使用匹配器,但它也不起作用。
英文:
I want to create routing for angular 2 application with urls starting with #. However, angular redirects to the home page instead of the component. How can I fix this problem?
I used matcher, and it doesn't work.
I use two urls for the same component, but it doesn't work with #. (urls: customcomponent and #/customcomponent). I also tried to use matcher but it also doesn't work.
答案1
得分: 1
默认的路由策略基于HTML5 History API,不在URL中使用'#'符号。如果你想在你的Angular 2应用程序中使用以'#'开头的URL,你需要不同地配置路由。
你可以使用Angular提供的"HashLocationStrategy"。这个策略在URL中使用哈希符号'#',并启用基于片段标识符的路由。
在你的app.module.ts文件中:
import { LocationStrategy, HashLocationStrategy } from '@angular/common';
@NgModule({
// ...
providers: [{ provide: LocationStrategy, useClass: HashLocationStrategy }],
// ...
})
export class AppModule { }
Angular将在URL中使用哈希符号,并相应地处理路由。例如,#/customcomponent将被识别为前往"CustomComponent"的路由。
一旦你做出这个更改,Angular将不再在使用以'#'开头的URL时重定向到主页。相反,它将根据你设置的路由配置正确地导航到指定的组件。
以下是一些参考链接:
- https://angular.io/api/common/HashLocationStrategy
- https://www.tektutorialshub.com/angular/angular-location-strategies/
英文:
Default routing strategy is based on the HTML5 History API, which does not use the '#' symbol in the URLs. If you want to use URLs starting with '#' in your Angular 2 application, you'll need to configure the routing differently.
You can use the "HashLocationStrategy" provided by Angular. This strategy uses the hash symbol '#' in the URLs and enables routing based on the fragment identifier.
In your app.module.ts
import { LocationStrategy, HashLocationStrategy } from '@angular/common';
@NgModule({
// ...
providers: [{ provide: LocationStrategy, useClass: HashLocationStrategy }],
// ...
})
export class AppModule { }
Angular will use the hash symbol in the URLs and handle routing accordingly. For example, #/customcomponent will be recognized as a route to the "CustomComponent".
Once you make this change, Angular will no longer redirect to the home page when using URLs starting with '#'. Instead, it will correctly navigate to the specified component based on the route configuration you have set up.
here some reference link
- https://angular.io/api/common/HashLocationStrategy
- https://www.tektutorialshub.com/angular/angular-location-strategies/
Hope it helpful..
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论