Skip to content Skip to sidebar Skip to footer

How To Change One Server Url To Another Server Url, If The Server Is Down In Angular6

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. Consider i h

Solution 1:

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

step 1:->

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

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

    // API urlwindow.__env.apiUrl = "http://RestWebService";

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

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 --><scriptsrc="env.js"></script></head><body>
    ...
    <!-- Angular code is loaded here --></body></html>

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

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 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"}],// ...}}}}}}}

step 2:->

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

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

@Injectable({
  providedIn: 'root'
})
exportclassEnvService {

  // The values that are defined here are the default values that can// be overridden by env.js// API urlpublic apiUrl = '';

  // Whether or not to enable debug modepublic enableDebug = true;

  constructor() {
  }

}

step 3:->

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

env.service.provider.ts

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

exportconstEnvServiceFactory = () => {  
  // Create envconst env = newEnvService();

  // Read environment variables from browser windowconst 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;
};

exportconstEnvServiceProvider = {  
  provide: EnvService,
  useFactory: EnvServiceFactory,
  deps: [],
};

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

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

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.

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 file

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

@NgModule({
  imports: [ // ... ],providers: [EnvServiceProvider],
})
exportclassAppModule {} 

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 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);
        returnthis._httpClinet.post(this.emplLoginCheckUrl, employeeDetails);
    }

tha's it for step 3.

step 4:->

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.

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/

Solution 2:

You can use ajax and if request fails, retry with other server url:

$.ajax({
        type: "POST",  
        url: "**serverIP** ",

        data: , 
        success: function(){  
            alert("done");  
        },
        error: function(XMLHttpRequest, errorThrown) { 
            alert("Here retry post with different server id "); 
        }       
});

Solution 3:

You could check if the request is getting failed and try making a request to another server but what if only the fourth server is working and you have to make three failed attempts all the time to reach the working one? Does not seem to be the most efficient way.

Instead, I would add an NGinx load balancer with health check: http://nginx.org/en/docs/http/load_balancing.html

Post a Comment for "How To Change One Server Url To Another Server Url, If The Server Is Down In Angular6"