How can I give an option to user to set baseurl?

Viewed 183

I have built an app using ionic but my clients will be using different servers for accessing API. How can I give an option to set the base url by the user to call the desired server API?

2 Answers

There are 2 ways:

The temporary way:

This way, when the app is closed, it reset to the default api:

  1. create a service ionic generate service
  2. in this service, make a variable that will have the url you need
  3. make some getter and setter
  4. import this service where you need it (were you change your api, and in your api service)

The permanent way:

Use the file plugin to make, for example, a JSON that you will read/write with the api url in it.

set your base url in environment.ts file and use in any of service

export  const  environment  = {
    production:  false,
    baseUrl:  'http://localhost:3000/'
};

auth.service.ts

import { Injectable } from '@angular/core';
import { Observable} from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../../environments/environment';

@Injectable({
    providedIn: 'root'
})
export class AuthService {
    baseUrl = environment.baseUrl;

    constructor(
        private http: HttpClient
    ) { }

    Userlogin(data: any): Observable<any> {
        return this.http.post(this.baseUrl + 'user/login', data);
    }
}
Related