如何在Ionic3中使用import导出带有逻辑的const [英] How to export const with logic using import in Ionic3
问题描述
我正在构建一个ionic3应用程序并遇到设置代理的问题。在Browser中,ionic会识别我的proxyUrl的路径,如下所示。
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"
}
]
}
但是,我遇到了离子会在我的代码中识别路径 / api
的问题,例如在get call this.http.get(' / 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.
所以要修复我尝试执行以下操作,如果我在浏览器(mobileweb)中设置路径 / api
否则设置我想要点击的网址。
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.
在上抛出错误是(...)
说 [ts]属性类型'typeof Platform'上不存在'is'。
我可以通过不同方式实现这一点来导出我想要的网址检查我所在的平台?
Any way I can implement this differently to export the url I want to by checking the platform I am on?
更新
我尝试了以下内容由于错误的网址在模拟器中出现错误,因此返回false:
I tried the following that returns false as I get errors in emulator because of wrong url:
返回false
import { Platform } from 'ionic-angular';
let platform = new Platform();
export const api = (Platform.is('mobileweb')) ? "/api" : "https://www.example.net/api";
要在构造函数中测试,它返回true。
To test in constructor it returns true.
返回true
export class Test {
constructor(platform: Platform){
console.log('InBrowser', platform.is('mobileweb'));
}
}
推荐答案
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";
}
}
用法
import { GlobalProvider } from '../../providers/my-config';
export class Test {
constructor(globalProvider: GlobalProvider){
console.log(globalProvider.api)
}
}
这篇关于如何在Ionic3中使用import导出带有逻辑的const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!