[英]Angular - Setup Base Route Parameters for app-routing
Working on an Angular v12 application.处理 Angular v12 应用程序。 Goal is to add /countryCode to the base url of the application so whenever the domain name is opened it automatically sends to domainName/countryCode.
目标是将 /countryCode 添加到应用程序的基础 url 中,以便在打开域名时自动发送到 domainName/countryCode。
The country code will be added either from localStorage if it was chosen previously (if it exists in the localStorage) otherwise a default country code "us" will be added.如果之前选择了国家代码(如果它存在于 localStorage 中),则将从 localStorage 添加国家代码,否则将添加默认国家代码“us”。
For example: When localhost:4200/ is opened it should automatically redirect to localhost:4200/us/例如:当 localhost:4200/ 打开时,它应该自动重定向到 localhost:4200/us/
That part is done .那部分已经完成。
Issues:问题:
Currently returns me to localhost:4200/sa
instead of localhost:4200/sa/products
目前将我返回到
localhost:4200/sa
而不是localhost:4200/sa/products
Code: Added :countryCode
route param to the app-routing.module代码:将
:countryCode
路由参数添加到 app-routing.module
const routes: Routes = [
{
path: '',
component: DefaultLayoutComponent,
children:
[
{ path: ':countryCode', component: HomeComponent },
]
},
]
DefaultLayoutComponent:默认布局组件:
constructor(){
let countryId: string;
if(this.localStorageService.getStorage("selectedCountry")){
countryId = this.localStorageService.getStorage("selectedCountry");
}
else {
countryId = "us";
}
this.router.navigate(['/'+countryId]);
}
HomeComponent:家庭组件:
constructor(){
let selectedCountry;
this.route.params.subscribe((params) => {
selectedCountry = params.countryCode;
});
this.localStorageService.setStorage('selectedCountry', country);
this.router.navigate(['/'+country]);
}
One solution is to use query parameter.一种解决方案是使用查询参数。 You need not
:countryCode
in your routes.您不需要
:countryCode
在您的路线中。
const routes: Routes = [
{
path: '',
component: HomeComponent ,
},
]
HomeComponent主页组件
constructor(
private router: Router,
private activatedRoute: ActivatedRoute,
) {}
ngOnInit(): void {
let countryCode = this.activatedRoute.snapshot.queryParams.countryCode;
if (countryCode == null ) {
if(this.localStorageService.getStorage("selectedCountry")){
countryCode = this.localStorageService.getStorage("selectedCountry");
} else {
countryCode = "us";
}
this.localStorageService.setStorage('selectedCountry', country);
this.router.navigate(['/'], { queryParams: { countryCode } });
}
}
In this case, URL will be localhost:4200/?countryCode=us
and localhost:4200/products?countryCode=us
and so on.在这种情况下,URL 将是
localhost:4200/?countryCode=us
和localhost:4200/products?countryCode=us
等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.