问题
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