如何使用两个url运行一个angular应用程序



想知道有没有办法用两个渲染URL运行一个angular 6应用程序?

示例:

www.domain.com/abc1

www.domain.com/abc2

我们有两个url,它们将使用相同的应用程序,但不同的是,无论何时呈现abc1,所显示的数据都与abc2不同。两者共享相同的代码/应用程序。

不知道如何做到这一点或那一点是可能的?

如果数据来自后端,并且Angular应用程序的数据源不同,则应该尝试以下操作:

ng build --prod --base-href "/abc1/"
ng build --prod --base-href "/abc2/"

您可以根据要加载的视图创建不同的布局。

列出的其他方法的另一种方法是实际使用相同的应用程序,只是在不同的路线上。

假设您正在列出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段/路由参数参数化所有设置。

相关内容

最新更新