[英]How to run one angular app with two urls?
想知道我們可以通過兩種渲染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段/ route參數對所有設置進行參數化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.