How to export const with logic using import in Ionic3

為{幸葍}努か 提交于 2019-12-23 04:42:01

问题


I am building an ionic3 app and running into a problem with setting a proxy. In Browser ionic will recognize the path of my proxyUrl like below.

ionic.config.json

{
  "name": "myApp",
  "app_id": "",
  "v2": true,
  "typescript": true,
  "proxies": [
    {
      "path": "/api",
      "proxyUrl": "https://www.example.net/api"
    }
  ]
}

However, I run into the issue where ionic will recognize the path /api in my code for example in a get call this.http.get('/api')... but will not recognize the path in emulator or on device.

So to fix that I tried doing the following, if I am in a browser (mobileweb) set path to /api otherwise set the URL I want to hit.

my-config.ts

import { Platform } from 'ionic-angular';

export const api = (Platform.is('mobileweb')) ? "/api" : "https://www.example.net/api";

This won't work though because I cannot access Platform directly here.

Throwing an error on the is(...) saying [ts] Property 'is' does not exist on type 'typeof Platform'.

Any way I can implement this differently to export the url I want to by checking the platform I am on?

UPDATE

I tried the following that returns false as I get errors in emulator because of wrong url:

Returns false

import { Platform } from 'ionic-angular';

let platform = new Platform();

export const api = (Platform.is('mobileweb')) ? "/api" : "https://www.example.net/api";

To test in constructor it returns true.

Returns true

export class Test {

    constructor(platform: Platform){
      console.log('InBrowser', platform.is('mobileweb'));
    }
}

回答1:


my-config.ts

import { Injectable } from '@angular/core';
import { Platform } from 'ionic-angular';

@Injectable()
export class GlobalProvider {
    public api: any;
    constructor(platform: Platform){
       this.api = (platform.is('mobileweb')) ? "/api" :"https://www.example.net/api";
    }
}

Usage

import { GlobalProvider } from '../../providers/my-config';
export class Test {

    constructor(globalProvider: GlobalProvider){ 
           console.log(globalProvider.api)
    }
}


来源:https://stackoverflow.com/questions/45242974/how-to-export-const-with-logic-using-import-in-ionic3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!