我尝试使用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
我想有两条可能的路线:
这似乎很容易,对吧?
这是我在特定模块中的路由定义:
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中添加了路由器插座标记
在我的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服务)在本地和生产模式,它也运作良好(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(好吧,那不行......)
有人有想法吗?非常感谢你的帮助。
这与Angular无关。您正在使用/TestRouting
重写URL并忽略查询字符串,请尝试以下操作:
<action type="Rewrite" url="/TestRouting" appendQueryString="true" />
感谢@ritaj,我使用the HashLocation strategy解决了这个问题。它改变了网址模板,但效果很好!