udith
udith

Reputation: 13

Error of appending http headers in ionic3?

I have to append header with all Http requests. But now none of my api call works.

In the below-mentioned code the first function is my HTTP request get.The second function appends header.

//http service to get
get(subUrl?:string, params?:object) {
        let optionalParam:URLSearchParams = new URLSearchParams();
        if (params) {
            for (let item in params) {
                optionalParam.set(item, params[item]);
            }
        }
        return this.createCustomHeader()
            .switchMap((headers)=> {
                console.log('headers inside swithmap', headers);
                return this.http.get(this.url + subUrl,
                    {search: optionalParam, headers: headers})
                    .map(response => response.json())
                    .catch(this.handleError)
            });
    }


//function to append header

    private createCustomHeader() {
        return Observable.create(obse=> {
            this.dbservice.getToken().subscribe(res=> {
                let headers = new Headers();
                console.log('fetch token', res);
                headers.append('Authorization ', `Bearer ${ res.access }`)
                headers.append('Content-Type', 'application/json');
                headers.append('Accept', 'application/json');
                obse.next(headers);
                obse.complete();
            })
        });
    }

function to get token

getToken() : Observable<any>{
    return Observable.create(obse=>{
        let db = new SQLite();
        db.create({
            name: "data.db",
            location: "default"
        }).then((db: SQLiteObject) => {
            db.executeSql('SELECT token,refresh_token FROM login',[])
                .then(res => {
                    if (res.rows.length > 0) {
                        for (var i = 0; i < res.rows.length; i++) {
                             this.token=(res.rows.item(i).token);
                             this.refresh_token=(res.rows.item(i).refresh_token);
                            if(this.token && this.refresh_token){
                                // console.log('Both token found');
                                const tok={'access':this.token ,'refresh':this.refresh_token};
                                // console.log('edfghjhgfdfghjhgfdsdfghj--99--',tok);
                                obse.next(tok);
                            }else {
                                obse.next(false);
                            }
                            obse.complete();
                        }
                    }else
                    {
                        obse.next(false);
                        obse.complete();
                    }
                })
                .catch(e => {
                    obse.error(e);
                    // console.log(e);

                });
        }).catch(e => {
            // console.log(e);
            obse.error(e);

        });
    });

}

Please, correct me. Thanks

Upvotes: 1

Views: 348

Answers (2)

Sayooj
Sayooj

Reputation: 375

Few things to note

  • You should fetch the token from db after platform ready .
  • Once you fetch token , use BehaviourSubject next . In your database service ,create a behaviour subject

    tokenSub= new BehaviorSubject({}); accessToken(){ return this.tokenSub.getValue(); }

    In the callback of getToken()

    this.tokenSub.next(tok);

    Append header
    `private createCustomHeader() {

    let token = this.dbservice.accessToken();
    let header = new Headers();
    if (token.hasOwnProperty('access')) {
        header.append('Authorization', 'Bearer ' + token['access']);
    }
    header.append('Content-Type', 'application/json');
    header.append('Accept', 'application/json');
    return header;
    

    }`

Upvotes: 1

Amir
Amir

Reputation: 2022

Declare header outside the method.

private headers = new Headers({ 'Content-Type': 'application/json' });

And inside the method set header like below.

this.headers.set('Authorization ', `Bearer ${ res.access }`)
this.headers.set('Accept', 'application/json');

Hope this help.

Upvotes: 0

Related Questions