我尝试使用 Angular 路由器,但在部署应用程序时遇到了一些麻烦。首先,这是我的版本:
Angular CLI: 6.2.3
Node: 9.11.1
OS: win32 x64
Angular: 6.1.9
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router
Package Version
-----------------------------------------------------------
@angular-devkit/architect 0.8.3
@angular-devkit/build-angular 0.8.3
@angular-devkit/build-optimizer 0.8.3
@angular-devkit/build-webpack 0.8.3
@angular-devkit/core 0.8.3
@angular-devkit/schematics 0.8.3
@angular/cli 6.2.3
@ngtools/webpack 6.2.3
@schematics/angular 0.8.3
@schematics/update 0.8.3
rxjs 6.2.2
typescript 2.9.2
webpack 4.20.2
我想有 2 条可能的路线:
- mydomain.com/TestRouting/my-route
- mydomain.com/TestRouting/my-route?route=whatever
这似乎很容易,对吧?
这是我在特定模块中的路由定义:
import ...
const appRoutes = [
{ path: 'my-route', component: RouteComponent },
{ path: '', redirectTo: '/my-route', pathMatch: 'full' }
];
@NgModule({
imports: [
CommonModule,
RouteModule, // This is a module containing the RouteComponent
RouterModule.forRoot(appRoutes)
],
declarations: [],
exports: [
RouterModule
]
})
export class RoutingModule { }
当然,我已经在 AppModule 中导入了这个模块,在 app.component.html 中添加了 router-outlet 标记
在我的 RouteComponent 中,我以这种方式获取查询参数:
export class RouteComponent implements OnInit {
urlParam: string;
constructor(private route: ActivatedRoute) { }
ngOnInit() {
console.log(this.route.snapshot);
this.urlParam = this.route.snapshot.queryParams['route'];
}
}
因为,我已经在 IIS 服务器上部署了网站,所以我添加了这个 web.config 文件:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="routes" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
<add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
</conditions>
<action type="Rewrite" url="/TestRouting" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
问题:在本地,它运行良好......(ng serve)在本地和生产模式下,它也运行良好(ng serve --prod)
我使用以下命令构建应用程序: ng build --base-href /TestRouting/ --prod
部署后,
mydomain.com/TestRouting/重定向到mydomain.com/TestRouting/my-route(预期行为) mydomain.com/TestRouting/my-route呈现组件(预期行为)但 mydomain.com/TestRouting/my-route?route=测试重定向到mydomain.com/TestRouting/my-route(好吧,那不行......)
有人有想法吗?非常感谢你的帮助。