获取Angular 2中的绝对应用URL

时间:2016-12-06 16:01:10

标签: javascript angular

有没有办法获取我的Angular 2应用的绝对网址,包括<base href="">

我需要将重定向网址发送到我的其他API以进行Twitter身份验证。 Twitter将获得这些并在成功验证后将用户重定向到他们。

所以我需要这样的东西,但动态absoluteBaseUrl动态(取决于环境):

// 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 个答案:

答案 0 :(得分:1)

您可以尝试这样的操作,在根组件中创建文件appConfig.service.ts

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));
    }
}

然后在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
    }
  }
}

因此,您可以根据此处的环境定义任何 baseUrl

并在任意 service.ts文件中使用此功能:

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;
  }
}

希望这会对你有所帮助。