如果服务器在 angular6 中关闭,如何将一个服务器 URL 更改为另一个服务器 URL [英] How to change one server URL to another server URL, if the server is down in angular6

查看:21
本文介绍了如果服务器在 angular6 中关闭,如何将一个服务器 URL 更改为另一个服务器 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 4 个具有不同 URL 的服务器,如果服务器在 angular 6 应用程序中关闭,我想将一个服务器 URL 更改为另一个服务器 URL,如果有人知道请帮助我.

I have 4 servers with different URLs, i want to change one server URL to another server URL if server is down in angular 6 application, if anyone knows please help me.

考虑到我有 4 个服务器具有不同的 URL(第 1、第 2、第 3 和第 4),这里第 1 个服务器具有更高的优先级,我想让它具有默认值.我的问题是如何将第 1 个服务器 URL 更改为与第 3 个和第 4 个相同的第 2 个服务器 URL,如果服务器已关闭.任何帮助将不胜感激,并提前致谢.

Consider i have 4 servers with different URLs(1st,2nd,3rd and 4th), here 1st server is having more priority and i want to make it has default. and my question is how to change 1st server URL to 2nd server URL as same as for 3rd and 4th also, if servers are down. Any help would be appreciated and thanks in advance.

service.ts 文件

service.ts file

firstserver ="http://111.121.1.342:8001/rest/formalities";
secondserver="http://111.121.1.342:8002/rest/formalities";
thirdserver="http://111.121.1.342:8003/rest/formalities";
fourthserver="http://111.121.1.342:8004/rest/formalities";

validateUserDetails(employeeDetails): Observable<any> {
    console.log(serversurl);
    return this._httpClint.post(serversurl(would be first/second/third/fourth server), employeeDetails);
}

在这里我必须检查第一个服务器 URL 是启动还是关闭,然后应用到哪个服务器 URL 启动.

here i have to check first server URL is up or down then apply to server URL which one is up.

预期结果:

我应该能够根据上下条件将一个服务器 URL 更改为另一个服务器 URL.

I should be able to change one server URL to another server URL based on up and down condition.

推荐答案

对于我上面的问题,我得到了如下解决方案,为此我们必须从 JAVASCRIPT 获得帮助.

for my above problem i got solution like in below, for that we have to take help from JAVASCRIPT.

第一步:->

在index.html目录下创建env.js文件,如下图.

create env.js file in the directory of index.html, like in below.

(function (window) {
    window.__env = window.__env || {};

    // API url
    window.__env.apiUrl = "http://RestWebService";

    // Whether or not to enable debug mode
    // Setting this to false will disable console output
    window.__env.enableDebug = true;
  }(this));

上面 env.js 文件的意义只是我们创建了一个名为 apiUrl 的全局变量,用于存储我们的服务器 URL.这样我们就可以全局访问该变量.接下来,我们在 index.html 的部分中添加一个元素,以便在加载 Angular 之前加载 env.js:

the meaning of above env.js file is just we are creating one global variable called apiUrl, to store our server URL. So that we can access that variable globally. Next, we add a element to the section in our index.html to load env.js before Angular is loaded:

<html>

  <head>
    <!-- Load environment variables -->
    <script src="env.js"></script>
  </head>

  <body>
    ...
    <!-- Angular code is loaded here -->
  </body>  

</html>  

默认情况下,当我们构建应用程序时,诸如 env.js 之类的 JavaScript 文件不会复制到输出目录中.

By default, JavaScript files such as env.js are not copied to the output directory when we build our application.

为了确保在运行 ng build 或 ng serve 时将文件复制到输出目录,我们必须将其添加到 angular.json 中应用程序构建配置的资产部分:

To make sure that the file is copied to the output directory when we run ng build or ng serve, we must add it to the assets section of our application's build configuration in angular.json:

angular.json 文件

angular.json file

{
  "projects": {
    "app-name": {
      "architect": {
        "build": {
          "options": {
            "assets": [
              "src/favicon.ico",
              "src/assets",
              "src/env.js"
            ]
          }
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              // ...
            }
          }
        }
      }
    }
  }
}

第 2 步:->

以 any 的名称创建一个服务,在我的例子中,我在 app.module.ts 目录中将其创建为 env.service.ts.这是一个服务文件,用于获取我们的服务器 URL 值,它存储在 apiUrl(env.js 文件)中.

Create one service in the name of any, in my case i created it as env.service.ts in the directory of app.module.ts. this is a service file will be used to take our server URL value, which is stored in apiUrl(env.js file).

env.service.ts

env.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class EnvService {

  // The values that are defined here are the default values that can
  // be overridden by env.js

  // API url
  public apiUrl = '';

  // Whether or not to enable debug mode
  public enableDebug = true;

  constructor() {
  }

}

第 3 步:->

在 env.service.ts 的同一目录中创建服务提供者文件.

Create on service provider file in the same directory of env.service.ts.

env.service.provider.ts

env.service.provider.ts

import { EnvService } from './env.service';

export const EnvServiceFactory = () => {  
  // Create env
  const env = new EnvService();

  // Read environment variables from browser window
  const browserWindow = window || {};
  const browserWindowEnv = browserWindow['__env'] || {};

  // Assign environment variables from browser window to env
  // In the current implementation, properties from env.js overwrite defaults from the EnvService.
  // If needed, a deep merge can be performed here to merge properties instead of overwriting them.
  for (const key in browserWindowEnv) {
    if (browserWindowEnv.hasOwnProperty(key)) {
      env[key] = window['__env'][key];
    }
  }

  return env;
};

export const EnvServiceProvider = {  
  provide: EnvService,
  useFactory: EnvServiceFactory,
  deps: [],
};

EnvServiceProvider:->它是一个Angular提供者配方,用于将带有Angular依赖注入的EnvServiceFactory注册为实例化EnvService的工厂.

EnvServiceProvider:->It is an angular provider recipe to register EnvServiceFactory with Angular dependency injection as the factory for instantiating EnvService.

EnvServiceFactory:->它是一个从 window.__env 读取环境值并实例化 EnvService 类的实例的工厂.

EnvServiceFactory:->It's a factory that reads environment values from window.__env and instantiates an instance of the EnvService class.

因此,在这个 env.service.provider.ts 文件的所有摘要中,我们导出了一个 EnvServiceFactory 函数,该函数创建了 EnvService 类的实例,并将 window.__env 对象中的所有值复制到 EnvService 实例中.

So over all summary of this env.service.provider.ts file is, we export an EnvServiceFactory function that creates an instance of the EnvService class and copies all values from the window.__env object into the EnvService instance.

最后,要在 Angular 的依赖注入系统中将 EnvServiceProvider 注册为配方,我们必须将其列为应用程序的 providers 数组中的提供者:

Finally to register EnvServiceProvider as a recipe with Angular's dependency injection system, we must list it as a provider in our application's providers array:

app.module.ts 文件

app.module.ts file

import { NgModule } from '@angular/core';  
import { EnvServiceProvider } from './env.service.provider';

@NgModule({
  imports: [ // ... ],
  providers: [EnvServiceProvider],
})
export class AppModule {} 

我们现在可以通过注入 EnvService 从我们应用程序的任何地方访问我们的环境变量,我正在使用它,如下所示.

We can now access our environment variables from anywhere in our application by injecting the EnvService, I am using it like in below.

service.ts 文件

service.ts file

import { EnvService } from '../env.service';

   constructor(private _httpClinet: HttpClient, private env: EnvService) {
    }

emplLoginCheckUrl = this.env.apiUrl+"/checkValidUser";

 validateUserDetails(employeeDetails): Observable<any> {
        console.log(this.emplLoginCheckUrl);
        return this._httpClinet.post(this.emplLoginCheckUrl, employeeDetails);
    }

就是第 3 步.

第 4 步:->

最后我们要做的就是在服务应用程序之前,我们必须使用 ng build --prod 构建应用程序以获取包含 env.js 文件的 dist 文件夹.从那里我们可以更改我们的 URL,如果您在那里更改 URL,它将自动在我们的应用程序中应用新更改的 URL.

finally what we have to do means before serving app, we have to build app with ng build --prod to get dist folder, which contains env.js file. from there we can change our URL's, if you change URL there it will automatically apply new changed URL in our application.

有关更多信息,请访问以下网站,感谢 Jurgen Van de Moere.

FOR MORE INFORMATION visit below site, thx Jurgen Van de Moere.

https://www.jvandemo.com/how-to-use-environment-variables-to-configure-your-angular-application-without-a-rebuild/

这篇关于如果服务器在 angular6 中关闭,如何将一个服务器 URL 更改为另一个服务器 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆