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

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

问题描述

我有4个具有不同URL的服务器,如果服务器在角度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(第一,第二,第三和第四)的服务器,这里第一台服务器具有更高的优先级,我想使其具有默认值.我的问题是,如果服务器宕机,如何将第一台服务器的URL更改为第二台服务器的URL,与第三台和第四台的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.

步骤1:->

在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中应用程序的构建配置的Assets部分:

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:->

以任何名称创建一个服务,就我而言,我在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依赖注入的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数组中将其列为provider:

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来构建应用程序,以获取dist文件夹,该文件夹包含env.js文件.从那里我们可以更改我们的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.

查看全文

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