Angular 12 区域环境切换器

huangapple go评论61阅读模式
英文:

Angular 12 Regional Environment Switcher

问题

我有一个简单的Angular网站,显示来自数据库的各种产品,最初只在英国,但现在还有一个在法国发布,所以我有两个API,一个是uk.domain,另一个是fr.domain。

我想要使用相同的前端而不是部署两个单独的前端,只需在两个页面上更改加载的产品即可。

除此之外,我还有包含必要端点的environment.dev.ts和environment.prod.ts文件。

理想情况下,一旦部署完成,我想要一个按钮来在不同地区之间切换。

这是否可行或者是否不良做法?如果是,最佳解决方案是什么?

英文:

I have a simple angular website which displays various products, simple lists returned from databases, originally just based in the UK but now another due to come out in France, so I have two APIs a uk.domain and a fr.domain.

I'd like to use the same frontend rather than deploying two separate frontends, with the switch only changing the products that are loaded on two of the pages.

Along with this I also have environment.dev.ts and environment.prod.ts files containing the necessary endpoints.

Ideally I'd have a button to switch between the regions once this has been deployed.

Is this possible or bad practice, if so, what would be the best solution?

答案1

得分: 3

如果数据模型对两个API都相同,您可以在用户界面中使用简单的切换来实现这一点。之后,有多种方法可以获取用户的位置,以便自动猜测正确的API。例如:地理定位API

切换端点的示例:

export const environment = {
  production: true,
  apiEndpoints: {
    uk: 'https://uk.domain/api',
    fr: 'https://fr.domain/api'
  }
};

export class ProductService {
  constructor(private http: HttpClient) {}

  getProducts(region: 'uk' | 'fr') {
    const apiEndpoint = environment.apiEndpoints[region];
    return this.http.get(`${apiEndpoint}/products`);
  }
}
英文:

If the datamodel is the same for both apis, you can do this with a simple switch in the ui. Later there multiple ways to get the users location so you can automatically guess the right api. For example: geolocator api

Example for switching the endpoint:

export const environment = {
  production: true,
  apiEndpoints: {
    uk: 'https://uk.domain/api',
    fr: 'https://fr.domain/api'
  }
};

export class ProductService {
  constructor(private http: HttpClient) {}

  getProducts(region: 'uk' | 'fr') {
    const apiEndpoint = environment.apiEndpoints[region];
    return this.http.get(`${apiEndpoint}/products`);
  }
}

huangapple
  • 本文由 发表于 2023年6月19日 21:37:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76507184.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定