Search code examples
angularhttpcapacitor

Angular - capacitor Angular http request doesn't work on android build


On desktop or mobile in browser (firefox) calling my backend endpoint returns the result I'd like (json object), however on capacitor android build I get an html response that is auto generated by capacitor. There is a comment in the html:

/**
         * API is not implemented.
         *
         * This usually means the API can't be used because it is not implemented for
         * the current platform.
         */

I've tried seraching for the error, but I couldn't find any results except, that capacitor has an http plugin, but I wouldn't like to rewrite my code changing all angular http to capacitor http. Are there any other solutions for this issue? Package versions:

  • angular/core: 15.2.0
  • capacitor/android: 4.7.0
  • capacitor/angular:2.0.3
  • capacitor/core: latest
  • capacitor/ios: 4.7.0

Http request:

function(id: string): Observable<any> {
return this.http.get<any>(`/api/endpoint/${id}`);
}

Solution

  • You dont include your base url. So it will indeed set default to the current domain, something like http://localhost/api/endpoint/${id} during local development.

    function(id: string): Observable<any> {
    return this.http.get<any>(`/api/endpoint/${id}`);
    }
    

    I would create environment.ts or some config.json

    and add one for dev and prod

    // environment.ts
    export const environment = {
      production: false,
      api_base_url: 'http://localhost:3000' // your api url
    };
    

    after that you could use it like this.

    import { environment } from '../environments/environment';
    
    ...
    
    function(id: string): Observable<any> {
      return this.http.get<any>(`${environment.api_base_url}/api/endpoint/${id}`);
    }