对于列出的其他方法,另一种方法是实际使用相同的应用程序,只是在不同的路线上。
假设您正在列出 Todos,但在 /abc1 上,它们来自 server-1.com/api,在 /abc2 上,它们来自 server-2.com/api。
您首先要创建您的应用程序路由模块,以捕获 url 的“子域”(正如您所说的,尽管它实际上是一个虚拟目录)部分。所以,app-routing.module.ts 有这个路由:
const routes = [
{ path: ':subdomain', component: TodosComponent },
];
// and the rest of it.
(为简单起见,我不在这里做模块)。
所以现在您的 TodosComponent 只需读取“子域”并从适当的后端获取内容:
class TodosComponent implements OnInit {
// inject the backend service (or more) and activated route
constructor(private backend: BackendService,
private route: ActivatedRoute) {
}
// on init, get that route param
ngOnInit() {
this.route.params.subscribe(params => {
// catch the "subdomain" param
const subdomain = params.subdomain;
// now you'd move this to a service, but here:
if (subdomain === 'abc1') {
this.backend.get('http://server-1.com/api').subscribe(...);
} else if (subdomain === 'abc2') {
this.backend.get('http://server-2.com/api').subscribe(...);
} else {
// add more as needed here.
}
})
}
}
现在,当您在子域之间切换时,这将是完全作为 SPA 工作的同一个应用。
在实际的应用程序中,您的应用程序路由会将其传递给(惰性)模块,该模块将构建所有组件、服务等,以便您可以使用此 url 段/路由参数对所有设置进行参数化。