簡體   English   中英

如何在 Startup.cs 中使用 ASP.NET 核心的 Angular SPA 的參數管理 HTML5 路由回退?

[英]How to manage HTML5 route fallback with parameter for Angular SPA with ASP.NET Core in Startup.cs?

我正在搜索,但沒有找到任何答案,也許這里有聰明人知道該怎么做。 我有 Angular SPA,帶有 ASP.NET 核心后端。 在 Angular 我不想使用Hash Bang Routes 但我不知道如何配置路由,以便能夠刷新或進入帶有參數的 SPA 組件頁面。 例如: somewebsite.com/a5eccbd9 //where a5eccbd9 is a parameter

與我的問題最接近的示例,但僅路由到 SPA 的index.html

https://stackoverflow.com/a/61275033

https://weblog.west-wind.com/posts/2017/aug/07/handling-html5-client-route-fallbacks-in-aspnet-core#Letting-ASP.NET-Core-Handle-Client-Side-路線

https://weblog.west-wind.com/posts/2020/Jul/12/Handling-SPA-Fallback-Paths-in-a-Generic-ASPNET-Core-Server#handling-fallbacks-with-built-in-端點和路由處理

但是在被路由到文件之后,接下來如何處理參數並被重定向到正確的組件? 我的 Angular 路由:

const routes: Routes = [
...
  {
    path: '',
    component: FormComponent,
  },
  {
    path: ':id',
    component: FormComponent,
  },
...
];

index.html我有: <base href="/" />

在我的死胡同里,我不知道如何讓后端正確地重定向我。

嘗試這個:

 const routes: Routes = [... { path: '', component: FormComponent, }, { path: '/:id', component: FormComponent, }, ... ];

在您的 component.ts 中,您可以通過調用在 ngOnInit 方法上使用它來獲取 id:

 import { ActivatedRoute } from '@angular/router'; constructor( private route: ActivatedRoute ) { } ngOnInit() { const id = this.route.snapshot.params.id); }

實際上,Angular 的后備路由比我預期的要容易。 在后端我只需要添加端點映射:

app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapFallbackToFile("/{id}", "/index.html"); //<- added
                endpoints.MapFallbackToFile("/", "/index.html");
            });

And from now on after GET request: somewebsite.com/a5eccbd9 ASP.NET Core redirects it to the Angular SPA's index.html , and over there Angular's routing deal with that oryginal request by its own routing path: ':id', .

我也在考慮這里的解決方案: Angular2: How to access index.html querystring in App Component where from id Core I want to redirect it to: index.html?id={id}但是 Angular 似乎比我預期的要聰明。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM