Angular在以#开头的URL上进行路由时无法正常工作。

huangapple go评论65阅读模式
英文:

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时重定向到主页。相反,它将根据你设置的路由配置正确地导航到指定的组件。

以下是一些参考链接:

  1. https://angular.io/api/common/HashLocationStrategy
  2. 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

  1. https://angular.io/api/common/HashLocationStrategy
  2. https://www.tektutorialshub.com/angular/angular-location-strategies/

Hope it helpful..

huangapple
  • 本文由 发表于 2023年6月15日 06:37:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76477998.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定