ionic 3 Set default requests header from ionic storage

Viewed 10232

This question is a bit similar Ionic 2 - Get token from Storage value and set Header before HTTP Request ( not a duplicate)

But the issue is connected with returning a value from local storage.

I need to set the default header(Authorization token) for all requests. Must be a typical problem, but can't find a solution. And most of the available info - about setting it for each request. Which is simple, but not very reasonable. - why set for each request if possible to set for all.

i tried:

case #1:

import {Injectable} from "@angular/core";
import {BaseRequestOptions, RequestOptions, RequestOptionsArgs} from "@angular/http";
import { Storage } from '@ionic/storage';


    @Injectable()
    export class MyRequestOptions extends BaseRequestOptions {
      constructor(private storage: Storage) {
        super();
        this.headers.set('Content-Type', 'application/json');
      }
      merge(options?: RequestOptionsArgs): RequestOptions {
        const newOptions = super.merge(options);

        console.log("setting auth header");

        function setAuthHeader(storage) {
          return storage.get('jwt_token').then(value => {
            newOptions.headers.set('Authorization',`Bearer ${value}`);
            return newOptions;
          });
        }

        return setAuthHeader(this.storage).then(()=>{
          return newOptions;
        })
      }
    }

in this case it's just not compiling, but it's to show what do i want to do.

case #2:

@Injectable()
export class MyRequestOptions extends BaseRequestOptions {
  constructor(private storage: Storage) {
    super();
    this.headers.set('Content-Type', 'application/json');
  }
  merge(options?: RequestOptionsArgs): RequestOptions {
    const newOptions = super.merge(options);

    console.log("setting auth header");
    return this.getApiToken().flatMap( data => {
      newOptions.headers.set('Authorization',`Bearer ${data}`);
      return newOptions;
    });
  }

  getApiToken(): Observable<RequestOptions> {
    return Observable.fromPromise(this.storage.get('jwt_token'));
  }
}

(it is similar to mentioned SO topic), but .flatMap() throwing a error:

argument of type '(data: Headers) => RequestOptions' is not assignable to parameter of type '(value: Headers, index: number) => ObservableInput<{}>'. Type 'RequestOptions' is not assignable to type 'ObservableInput<{}>'. Type 'RequestOptions' is not assignable to type 'ArrayLike<{}>'. Property 'length' is missing in type 'RequestOptions'.

case #3:

let api_token = await this.storage.get('jwt_token'); -> await simply isn't work here.

Any idea?

2 Answers
Related