2

Is there a way to get the absolute URL of my Angular 2 app, including the <base href="">?

I need to send redirect URLs to my rest API for Twitter authentication. Twitter will get these and redirect the user to them upon successful authentication.

So I need something like this but with a dynamic absoluteBaseUrl dynamical (depends on environment):

// How do I avoid hardcoding this?
let absoluteBaseUrl = "https://example.com/app";

let redirectUrl = absoluteBaseUrl + "/authsuccess";

// authUrl will look something like: http://example.com/api/auth?redirect=http%3A%2F%2Fexample.com%2Fapp%2Fauthsuccess
let authUrl = ComposeTwitterAuthUrl(redirectUrl);

// Redirect the user to the Twitter auth screen
window.location.href= authUrl;

1 Answer 1

1

You can try something like this, Create file appConfig.service.ts in root component.

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

interface EndPoint {
  baseUrl: string;
  requiresAuthentication: boolean;
}

interface ResourceLocator {
  [key: string]: EndPoint;
}

interface XResourceLocator {
  x: ResourceLocator;
}

interface YResourceLocator {
  y: ResourceLocator;
}

@Injectable()
export class APIConfigurations implements XResourceLocator, YResourceLocator {
    private _config;

    constructor() {
     this._config = require("./apiConfig.json");
    } 

    public get x(): ResourceLocator {
      return this.clone(this._config.x);
    }

    public get y(): ResourceLocator {
      return this.clone(this._config.y);
    }

    private clone<T>(value: T): T {
      return JSON.parse(JSON.stringify(value));
    }
}

and then define your all urls in apiConfig.json:

{
  "x": {
    "apiary": {
    "baseUrl": "https://private-xyz.apiary-mock.com/test/",
    "requiresAuthentication": false
   },
   "local": {
     "baseUrl": "http://localhost:8080/test/",
     "requiresAuthentication": false
   }
 },
 "y": {
    "apiary": {
      "baseUrl": "https://private-xyz.apiary-mock.com/test1/",
      "requiresAuthentication": false
    },
    "local": {
       "baseUrl": "http://localhost:8080/test1/",
       "requiresAuthentication": false
    }
  }
}

So you can define any baseUrl based on the environment here.

And use this in your any service.ts file:

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import {APIConfigurations} from "../app/apiconfig.service";
import 'rxjs/Rx';


@Injectable()
export class DashboardService {

   private _requestOptions: RequestOptions;
   private _baseUrl: string;

   constructor(private http: Http, apiConfigs: APIConfigurations) {
    const headers = new Headers({ 'Accept': 'application/json' });
    const config = apiConfigs.x["local"];
    this._baseUrl = config.baseUrl;
    this._requestOptions = new RequestOptions({ headers: headers, withCredentials: config.requiresAuthentication });
   }

    /**
     * [getUsers list of users]
    */
   getUsers() {

       return this.http.get(this.resolveUrl(`users`), this._requestOptions)
                    .map(res => res.json())
                    .catch(this.handleError);
   }

  private handleError(error: Response) {
    return Observable.throw(error.json().error || 'Server error');
  }

  public resolveUrl(path: string): string {
    var normalized = this._baseUrl.endsWith("/")
                        ? this._baseUrl
                        : this._baseUrl + "/";

    return normalized + path;
  }
}

Hope this will help you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.