Utilizing import for Ionic3 to export const with logic

While developing an app using ionic3, I encountered an issue with setting up a proxy. When running in a browser, Ionic was able to recognize the path of my proxyUrl as shown below.

ionic.config.json

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

However, I faced a problem where Ionic would identify the path /api in my code (e.g., this.http.get('/api')...) but not on the emulator or device.

To address this, I attempted the following approach: if the platform is a browser (mobileweb), set the path to /api; otherwise, use the desired URL.

my-config.ts

import { Platform } from 'ionic-angular';

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

Unfortunately, this method failed because I couldn't directly access Platform in this context.

An error occurred at is(...), stating

[ts] Property 'is' does not exist on type 'typeof Platform'.

Is there an alternative way to implement this and export the URL based on the platform?

UPDATE

I experimented with the following code that resulted in false due to errors in the emulator caused by an incorrect URL:

Returns false

import { Platform } from 'ionic-angular';

let platform = new Platform();

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

In contrast, when testing in the constructor, it returned true.

Returns true

export class Test {

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

Answer №1

my-configuration.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";
    }
}

Example of Implementation:

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the steps to integrate an in-memory cache in an Angular frontend using GraphQL queries?

In our Angular frontend application, we are utilizing GraphQL queries with Apollo Client to fetch data. We are interested in implementing caching for our data retrieval process. Initially, we will query the data and store it in the cache. Subsequent requ ...

Updating All Values in "ng-repeat" Using AngularJS

I am facing an issue with ng-repeat where only the last value of "frais" is being updated. Is there a way to update all values displayed by ng-repeat? Here is the code from file.html: <ion-content class="padding" ng-controller="FactureAdminCtrl" ng-re ...

Obtain the angular version during the Azure build pipeline execution

Is there a way to retrieve the current version of Angular used in our project as we build it through the pipeline? We leverage Azure DevOps and utilize YML for configuring our pipelines. Although I have managed to extract the "key" for "angular/core" from ...

The 'ngForOf' directive cannot be bound to 'div' element as it is not recognized as a valid property

Encountering an issue with adding an ngFor directive on a div, which is causing a warning and preventing my HTML from rendering properly. I experimented with using *ngFor on various elements like <li>, <tr>, and <span>, but kept getting ...

Setting up AngularJS can be a pain

Greetings, my name is Rahim. While setting up AngularCLI, I ran into the following issue: 'ng' is not recognized as an internal or external command, operable program or batch file. C:\Users\ASUS ROG>ng --version 'ng' is ...

Access Azure-Active Directory through cypress tests

Currently, I'm faced with the task of creating automated tests for an application that requires login to Azure Active Directory. These tests are being written using Cypress and TypeScript. In search of a solution, I am seeking advice on how to execute ...

The setTimeout() function caught in an endless cycle

Is there a way to retrieve the height of divs used in multiple components? The HTML structure I am working with is as follows: <div #dataHeadlines *ngFor="let group of catt" [ngClass]='hf(dataHeadlines)'> <h4>{{ group }}< ...

What steps are needed to have typescript recognize a typed function as a throw-statement?

I'm grappling with a typescript issue - I have a custom function that consistently throws an error, which is used to handle null variables. Strangely, if I directly throw an error without using the function, typescript recognizes that the variable can ...

What's causing the subscription feature to malfunction in a fresh browser tab?

I am facing an issue with camera entries on an angular website. Whenever I click on an entry, a new window opens to display the camera livestream. However, I am having trouble with the subscribe functionality. Important note: Once the window is open, subs ...

Want to enhance user experience? Simply click on the chart in MUI X charts BarChart to retrieve data effortlessly!

I'm working with a data graph and looking for a way to retrieve the value of a specific column whenever I click on it, and then display that value on the console screen. Check out my Data Graph here I am using MUI X charts BarChart for this project. ...

A better choice than Java's <? super SomeType> in Typescript

Is there a scenario in which one of the generic parameters used to create an instance of my class should be a superclass of another class? In Java, this is easily achievable using <? super SomeType>. What would be the equivalent in TypeScript? ...

What is the process for automatically initiating a service when importing a module in Angular?

I am curious about how I can automatically run a service within a module upon importing it, without the need for manual service injection and execution. This functionality is similar to how the RouterModule operates. @NgModule({ imports: [ Browser ...

Tips for efficiently managing angular route subscriptions and leveraging parameters for simultaneous http requests

I am seeking the best solution for the following situation: My goal is to trigger two parallel http requests when an Observable from the route parameters subscription fires. I attempted to use switchMap in combination with forkJoin, but unfortunately it ...

Is there a compatibility issue between Nativescript and Angular Universal?

I am fairly new to Nativescript and recently attempted to incorporate Angular Universal building into an existing Angular 9/Nativescript application. However, I encountered the following error: [error] Error: Schematic "universal" not found in collect ...

Typescript often fails to recognize that every code path within a function should return a value

Is it possible to inform TypeScript that all potential code paths in a function will return a value? In my scenario, I provide two numeric arrays as input, verify their monotonically increasing nature, and then retrieve a value based on specific condition ...

Can you explain how to incorporate a node module script into a React.js project?

I have encountered an issue where the element works perfectly fine when using an external node module, but fails to function properly when using a locally downloaded node module. Unfortunately, I am unable to identify the root cause of this problem. You c ...

Error in Angular 2: Trying to access a property that is undefined - 'Symbol(Symbol.iterator)'

It appears that the error I am encountering is related to how I handle data when returning it. I have been unable to pinpoint where my return statement may be missing or if that is even the root cause of the issue... The error occurs when deleting somethin ...

The visual representation remains unchanged even after updating the model

I'm currently tackling an issue with my football project, specifically when updating a service model. The project involves two key components - AvailablePlayers and SelectedPlayers, as well as two corresponding services - AvailablePlayersService and S ...

Navigating to a child route from a parent component in Angular using the navigate method: A step-by-step guide

Here is the code snippet for my HTML routerLink: <a [routerLink]="['create']">Create</a> - it's working just fine. When I try to call the same on a button click, it doesn't work.. navigateTo(page) { this.router.na ...

Angular material stepper displaying incorrectly

Here is the HTML code I used for creating an Angular Material stepper: <mat-horizontal-stepper class="stepper"> <mat-step label="Basic" state="cloud_download"> Step 1 <button mat-button matSteppe ...