How to send headers on all Ionic HTTP requests 3

Asked

Viewed 834 times

0

My code is like this, I would like to know how to send an Authorization token in all http requests made in Ionic 3:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'page-categoria',
  templateUrl: 'categoria.html'
})
export class CategoriaPage {

  constructor(public nav: NavController, public httpClient: HttpClient) { }

  toTest() {

    let data = {};
    let url = 'https://localhost/gestor2.0/public/categoria/';
    let headers = new HttpHeaders({
      'Authorization': 'Bearer ' + 'TdSa4512csdgfa368747654'
    });

    this.httpClient.post(url, data, { headers: headers })
      .subscribe((result: any) => {
        console.log('sucesso ao salvar');
        console.log(result);
      },
        (error) => {
          console.log(error);
        });
  }

}

Returns this error when opening the category page:

core.js:1449 ERROR Error: Uncaught (in Promise): Error: Staticinjectorerror(Appmodule)[Categoriapage -> Httpclient]: Staticinjectorerror(Platform: core)[Categoriapage -> Httpclient]: Nullinjectorerror: No Provider for Httpclient! Error: Staticinjectorerror(Appmodule)[Categoriapage -> Httpclient]: Staticinjectorerror(Platform: core)[Categoriapage -> Httpclient]: Nullinjectorerror: No Provider for Httpclient! at Nullinjector.get (core.js:1003) resolveat Token (core.js:1301) at tryResolveToken (core.js:1243) At Staticinjector.get (core.js:1111) resolveat Token (core.js:1301) at tryResolveToken (core.js:1243) At Staticinjector.get (core.js:1111) resolveat NgModuleDep (core.js:10896) At Ngmoduleref.get (core.js:12129) resolveat Dep (core.js:12619) at c (polyfills.js:3) At Object.Reject (polyfills.js:3) At Tab.NavControllerBase. _fireError (Nav-controller-base.js:223) At Tab.NavControllerBase. _failed (Nav-controller-base.js:216) at Nav-controller-base.js:263 at t.invoke (polyfills.js:3) At Object.onInvoke (core.js:4760) at t.invoke (polyfills.js:3) at r.run (polyfills.js:3) at polyfills.js:3

2 answers

1

Good afternoon, it seems to me that the error presented is why you did not import Httpclientmodule.

Go to your app.module.ts and import the module.

import { NgModule }         from '@angular/core';
import { BrowserModule }    from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    // import HttpClientModule after BrowserModule.
    HttpClientModule,
  ],
  declarations: [
    AppComponent,
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

  • no no, I already import in appmodule

1


Hello!

I usually generate a Service to abstract HTTP methods:

import { environment } from '../../../environments/environment';
import {
   Http,
   RequestOptions,
   RequestOptionsArgs,
   Response,
   Request,
   Headers,
   XHRBackend
} from '@angular/http';

@Injectable()

export class Httpservices {

headers: HttpHeaders;
options: object;

constructor(private readonly http: HttpClient) { }

endpoint: string = environment.apiUrl; //pega o endereço do arquivo environments.ts

get( uri: string ) {
    return this.http.get( this.endpoint + uri ).pipe(
        tap((res: Response) => {
            this.onSuccess(res);
        }),
        retry(0),
        catchError(this.onCatch),
        finalize(() => this.onEnd())
    );
}

post(url: string, data): Observable<any> {

    return this.http.post( this.endpoint + url, data )
        .pipe(
            tap((res: Response) => {
                this.onSuccess(res);
            }),
            retry(0), // retry a failed request up to 3 times
            catchError(this.onCatch), // then handle the error
            finalize(() => this.onEnd())
        );
}

and in specific services as in your case - Categoriaservice* would look like this:

// o caminho da abstração das chamadas HTTP
import { HttpServices } from './http.services';

CategoriaService {

  URI = '/categoria'
  // injetando o Service Http criado
  constructor( private httpCustom: HttpServices) {

  }

  salvar( data ) {
    // ja retorna uma Observable
    return this.httpCustom.post( this.URI, data )
  }
}

and when using on a Page, the specific Service can be used.

In abstraction you can implement the default behaviors, which are required for each Http call.

I hope I helped. Hug

  • I understand, but I don’t want to use Service you understand, because I will only need this page.

  • I get it. Man, everything suggests that it is something in the app.module, import the Httpclientmodule and add in the Imports array, as in the @Ilvio-fields response. I researched about the error and most solutions lead to this solution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.