首页 > 解决方案 > Angular 8 + Angular PWA 路由不适用于直接 URL

问题描述

我正在使用 Angular PWA 在 Angular 8 中进行开发。在这里你可以找到我在说什么(现在通过 chrome 调试器在移动版本中测试它,否则你什么也看不到):https ://www.yeswelazio.it/test

我正确设置了我的路由规则:

const routes: Routes = [
  { path: '',                 component: AppComponent },

  // Mobile
  { path: 'mobile/home',      component: MobileHomeComponent },
  { path: 'mobile/archivio',  component: MobileArchiveComponent },
  { path: 'mobile/news/:id',  component: MobileNewsComponent },
  { path: 'mobile/contatti',  component: MobileContactsComponent },

  // Desktop
  { path: 'desktop/home',     component: DesktopHomeComponent },

  // Error
  { path: '**',               redirectTo: '' }
];

这是我的manifest.webmanifest文件:

 {
  "name": "Yes We Lazio",
  "short_name": "Yes We Lazio",
  "theme_color": "#1976d2",
  "background_color": "#fafafa",
  "display": "standalone",
  "scope": "/test/",
  "start_url": "/test/",
  "icons": [
    { "src": "assets/icons/icon-72x72.png",   "sizes": "72x72",   "type": "image/png" },
    { "src": "assets/icons/icon-96x96.png",   "sizes": "96x96",   "type": "image/png" },
    { "src": "assets/icons/icon-128x128.png", "sizes": "128x128", "type": "image/png" },
    { "src": "assets/icons/icon-144x144.png", "sizes": "144x144", "type": "image/png" },
    { "src": "assets/icons/icon-152x152.png", "sizes": "152x152", "type": "image/png" },
    { "src": "assets/icons/icon-192x192.png", "sizes": "192x192", "type": "image/png" },
    { "src": "assets/icons/icon-384x384.png", "sizes": "384x384", "type": "image/png" },
    { "src": "assets/icons/icon-512x512.png", "sizes": "512x512", "type": "image/png" }
  ]
}

不幸的是,我无法直接访问像https://www.yeswelazio.it/test/mobile/archivio这样的 URL,因为每次我尝试浏览器都会将我重定向到https://www.yeswelazio.it/test/mobile/家

我也尝试使用 {useHash: true} 并从我的路由规则中评论{ path: '**', redirectTo: '' } 。

我知道 Angular 路由,所以我认为这是因为 PWA。我该怎么做才能直接访问某些 URL?

标签: angularroutingangular-ui-routerangular-cliprogressive-web-apps

解决方案


我对 PWA 也有同样的问题,并为自己找到了一个解决方案。{ path: '**', redirectTo: '/home', pathMatch: 'full' }只需从您的 root中删除重定向app.routing.module.ts

例如,创建一个组件 404 并将其用于路由**。在这种情况下,用户将在任何未知路由上看到 404 组件,但浏览器中的 url 不会改变。

在 404 组件中,我检查更新:

import { SwUpdate } from '@angular/service-worker';
...
constructor(private swUpdate: SwUpdate) {}
...
this.swUpdate.available.subscribe(() => {
   // here you can reload your page
   window.location.reload();
});

现在您的应用程序将重新加载,用户将看到新页面而不是 404 组件。

在我的应用程序上,我在检查更新时为用户添加了一些信息。您可以在methodist.io上查看它,尝试编写任何自定义路线。


推荐阅读