javascript - 在 Angular 2 中获取绝对应用程序 URL

标签 javascript angular

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

我需要将重定向 URL 发送到我的其余 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;

最佳答案

您可以尝试这样的操作,在根组件中创建文件 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 中定义所有的 url:

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

希望对您有所帮助。

关于javascript - 在 Angular 2 中获取绝对应用程序 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40999666/

相关文章:

javascript - jQuery $ .ajax-从成功函数调用错误函数?

javascript - 无法使用 jQuery/Javascript 从表单中检索值

javascript - jQuery 打开外部 url 并操作 DOM

javascript - 我如何覆盖 sequelize defaultValue 函数以进行测试?

javascript - 我需要在带有 ngFor angular 5 的同一个选择框中给出州和地区的详细信息

angular - 安装 Angular 库 - 无法解析依赖树

javascript - Angular 2 View 在 ngOnInit 中加载数据之前呈现

angular - npm 运行 ionic :build --prod giving strange error

javascript - 检查页面是否卸载或导航

typescript - index.ts 中导出的自动排序会导致应用程序崩溃