HttpHeaders problem in providers

#1

app.module.ts

import {HttpClientModule} from "@angular/common/http";

imports: [

HttpClientModule

],

login-user.ts:

import { Injectable } from '@angular/core';
import {HttpClient} from "@angular/common/http";
import { Response } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class LoginUser {
 data:any;
  constructor(public http: HttpClient) { }

  loginUserAll(data:any) {
   return this.http.post('http://btrc.urbanitsolution.com/api/login.php',data,{ headers: new HttpHeaders().set('Content-Type', 'application/json')})
      .map((res: Response) => res.json())
  }

}

Error :
Typescript Error
Cannot find name ‘HttpHeaders’.

Error while running ionic android build --prod --release (@ionic-native/core/decorators.d.ts, found version 4, expected 3)
#2

You are frankensteining together incompatible Http clients. Get rid of all the imports aside from Injectable and HttpClient. There is no need for custom headers, the map operator, json(), or any of that.

#3

is this right?

import {HttpClient} from "@angular/common/http";
export class LoginUser {
 data:any;
  constructor(public http: HttpClient) { }

	loginUserAll(data:any) {
		let headers = new Headers({ 'Content-Type': 'application/json' });
		let options = new RequestOptions({ headers: headers });      
		this.http.post('http://btrc.urbanitsolution.com/api/login.php', data, options).subscribe(data => {
			   console.log(data);
		   }, error => {
			   console.log(error);
		   });
		
	}      
}

#4

As I said before, you do not need custom headers here. If data is an object, HttpClient will automatically set Content-Type to application/json. loginUserAll should only be one line long:

return this.http.post(url, data);
#5

Submitted Form

submitForm(value: any):void{
	let formValue = { 
	   email:value.email, 
	   password:value.password
	}; 
	this.loginUser.loginUserAll(formValue)
   .subscribe(
	 countries =>  console.log(countries),
	 error =>   console.log(error));
}

as you said providers:

import { HttpClient } from '@angular/common/http';
export class LoginUser {
 data:any;
  constructor(public http: HttpClient) { }
	loginUserAll(data:any) {
		return this.http.post('http://btrc.urbanitsolution.com/api/login.php', data);
	}      
}

Error:
Can’t resolve all parameters for LoginUser: (?).

#6

Weird, I get Can’t resolve all parameters for LoginUser: (?). when I import 2 providers on each other, that’s a circular dependency what you’re getting.

Do you have HttpClient imported from when you’re calling the method in LoginUser?

#7

You took @Injectable() off. It needs to still be there.

#8

providers:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class LoginUser {
 data:any;
  constructor(public http: HttpClient) { }
	loginUserAll(data:any) {
		return this.http.post('http://btrc.urbanitsolution.com/api/login.php', data);
	}      
}

login.ts

let datas = { 
   email:value.email, 
   password:value.password,
   product_session:values[0]
}; 
this.loginUser.loginUserAll(datas)
   .subscribe(
	 data =>  {
		 console.log(JSON.stringify(data));
		 let alert = this.alertCtrl.create({
			title: JSON.stringify(data),
			subTitle: 'Please check Internet yes Connection/Contact Development Team',
			buttons: ['Close']
		});
		alert.setMode("ios");
		alert.present();
		this.nav.setRoot(HomePage);
	 },
	 error =>   {
		 
		 let alert = this.alertCtrl.create({
			title: JSON.stringify(error),
			subTitle: 'Please check Internetw Connection/Contact Development Team',
			buttons: ['Close']
		});
		alert.setMode("ios");
		alert.present();
		this.nav.setRoot(HomePage);
	 });

in Browser it’s working but in mobile not.
Probably does not get link in mobile. shows below picture.

#9

Thats a CORS problem now due to WKWebView, it won’t work if use Angular’s HttpClient.

You have to use the Native HTTP from Ionic or this plugin that I highly recommend since it allows you to use Angular’s HttpClient, which is much better than Ionic’s HTTP Native: https://github.com/sneas/ionic-native-http-connection-backend

I recommend that plugin because, for example, Ionic Native HTTP doesn’t has automatic interceptors, while Angulars HttpClient has, aside of much more features.

#10

You recommand this plugin https://github.com/sneas/ionic-native-http-connection-backend
How will i use this plugin in providers?
will i use it with native api https://ionicframework.com/docs/native/http/?
I have installed your plugin and add my app.module.ts.
Any example code please? or link?

#11

Hi, just follow the installion guide and use Angular’s Http as you’d normally do. You don’t have to do anything else.

#12

app.module.ts

import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule,Platform } from 'ionic-angular';
import { HttpBackend, HttpXhrBackend } from '@angular/common/http';
import { NativeHttpModule, NativeHttpBackend, NativeHttpFallback } from 'ionic-native-http-connection-backend';
@NgModule({
  declarations: [
  MyApp,HomePage,Login,Logout
  ],
  imports: [
    BrowserModule,
	
    IonicModule.forRoot(MyApp,{
		mode: 'ios',
		backButtonText: ''
	}),
	//HttpModule,
	//HttpClientModule,
	NativeHttpModule,
	IonicStorageModule.forRoot()
  ],
  bootstrap: [IonicApp],
  entryComponents: [
   MyApp,HomePage,Login,Logout
  ],
  providers: [
    GoogleMaps,StatusBar,SplashScreen,LoginUser,UserData,AddRecent,
	//AppUpdate,
    {provide: ErrorHandler, useClass: IonicErrorHandler, HttpBackend, useClass: NativeHttpFallback, deps: [Platform, NativeHttpBackend, HttpXhrBackend]}
  ]
})

login.ts

submitForm(value: any):void{
	let datas = { 
	   email:value.email, 
	   password:value.password,
	   product_session:values[0]
	}; 
	this.loginUser.loginUserAll(datas)
   .subscribe(
	 data =>  {
		 console.log(JSON.stringify(data));
		 let alert = this.alertCtrl.create({
			title: JSON.stringify(data),
			subTitle: 'Data found',
			buttons: ['Close']
		});
		alert.setMode("ios");
		alert.present();
		this.nav.setRoot(HomePage);
	 },
	 error =>   {
		 
		 let alert = this.alertCtrl.create({
			title: JSON.stringify(error),
			subTitle: 'Data not found',
			buttons: ['Close']
		});
		alert.setMode("ios");
		alert.present();
	 });
}

login providers

import { Injectable } from '@angular/core';
import { HTTP } from '@ionic-native/http';
import { Platform } from 'ionic-angular';
@Injectable()
export class LoginUser {
 data:any;
  constructor(
	private platform: Platform,
        private nativeHttp: HTTP,
  ) { }
	loginUserAll(data:any) {
	this.platform.ready().then(() => {
            return this.nativeHttp.post('http://btrc.urbanitsolution.com/api/login.php', data);
        });
	}      
}

when i use “ionic serve --lab” then
error shows

#13

The error is telling you what’s happening. You have to pass three arguments even if empty such has this.nativeHttp.get(URL, {}, {})

#14

error shows HttpBackend in app.module.ts

 Argument of type '{ declarations: (typeof HomePage | typeof Login | typeof MyApp | typeof Logout)[];
            imports: (Modu...' is not assignable to parameter of type 'NgModule'. Types of property 'providers' are
            incompatible. Type '(typeof SplashScreen | typeof AddRecent | typeof UserData | typeof LoginUser | typeof
            GoogleMaps ...' is not assignable to type 'Provider[]'. Type 'typeof SplashScreen | typeof AddRecent |
            typeof UserData | typeof LoginUser | typeof GoogleMaps |...' is not assignable to type 'Provider'. Type '{
            provide: typeof ErrorHandler; HttpBackend: typeof HttpBackend; useClass: typeof IonicErrorHandl...' is not
            assignable to type 'Provider'. Object literal may only specify known properties, and 'HttpBackend' does not
            exist in type 'Provider'.

      L51:  //AppUpdate,
      L52:     {provide: ErrorHandler,HttpBackend,  useClass: IonicErrorHandler, NativeHttpFallback, deps: [Platform, Na
      L53:   ]

#15

I don’t really get what you’re trying to do. Using the library I recommended you or just trying to use the HTTP Native Plugin from Ionic?

#16

Providers

import { Injectable } from '@angular/core';
import { HTTP } from '@ionic-native/http';
import { Platform } from 'ionic-angular';
@Injectable()
export class LoginUser {
 data:any;
  constructor(
	private platform: Platform,
        private nativeHttp: HTTP,
  ) { }
	loginUserAll(data:any) {
		this.platform.ready().then(() => {
            return this.nativeHttp.post('http://btrc.urbanitsolution.com/api/login.php', data, {});
        });
	}      
}

login.ts

let datas = { 
   email:value.email, 
   password:value.password,
   product_session:values[0]
}; 
this.loginUser.loginUserAll(datas).subscribe(
 data =>  {
	 console.log(JSON.stringify(data));
	 let alert = this.alertCtrl.create({
		title: JSON.stringify(data),
		subTitle: 'Please check Internet yes Connection/Contact Development Team',
		buttons: ['Close']
	});
	alert.setMode("ios");
	alert.present();
	this.nav.setRoot(HomePage);
 },
 error =>   {
	 
	 let alert = this.alertCtrl.create({
		title: JSON.stringify(error),
		subTitle: 'Please check Internetw Connection/Contact Development Team',
		buttons: ['Close']
	});
	alert.setMode("ios");
	alert.present();
 });

Error shows:

#17

Ionic’s Native HTTP uses Promises, not Observables. You either have to:

1-. Change in your page this.loginUser.loginUserAll(datas).subscribe... to this.loginUser.loginUserAll(datas).then...

2-. Or convert the Promise to an Observable if you want to use Observables instead of a Promise. For this, do :

import { fromPromise } from 'rxjs/observable/fromPromise';

and then use it like this:

return fromPromise(this.nativeHttp.post('http://btrc.urbanitsolution.com/api/login.php', data, {}))

in your provider

#18

if i chnage login.ts . I have change it “then” but

this.loginUser.loginUserAll(datas).then(data => {

    console.log(data.status);
    console.log(data.data); // data received by server
    console.log(data.headers);

  })
  .catch(error => {

    console.log(error.status);
    console.log(error.error); // error message as string
    console.log(error.headers);

  });

error shows:
**`Property ‘then’ does not exist on type ‘void’.

  L62:                      };
  L63:                      this.loginUser.loginUserAll(datas).then(data => {`**

or
if i change providers

mport { Injectable } from '@angular/core';
import { HTTP } from '@ionic-native/http';
import { Platform } from 'ionic-angular';
import { fromPromise } from 'rxjs/observable/fromPromise';
@Injectable()
export class LoginUser {
 data:any;
  constructor(
	private platform: Platform,
        private nativeHttp: HTTP,
  ) { }
	loginUserAll(data:any) {
		this.platform.ready().then(() => {
          return fromPromise(this.nativeHttp.post('http://btrc.urbanitsolution.com/api/login.php', data, {}))
        });
	}      
}

then error come

**Property 'subscribe' does not exist on type 'void'.**

**      L62:  };**
**      L63:  this.loginUser.loginUserAll(datas).subscribe(**
**      L64:       data =>  {**
#19

You have to set a return value to your provider’s method.

If you use option 1:

loginUserAll(data:any): Promise<any>

If you use option 2:

loginUserAll(data:any): Observable<any>
#20
loginUserAll(data:any):Promise<any> {
		this.platform.ready().then(() => {
          return fromPromise(this.nativeHttp.post('http://btrc.urbanitsolution.com/api/login.php', data, {}))
        });
	} 

error
A function whose declared type is neither 'void' nor 'any' must return a value.
what i am missing?