1

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

2
  • Will you please explain this "return Observable.create" inside createCustomHeader ? Commented Oct 25, 2017 at 6:55
  • actually i m fetching token from db Commented Oct 25, 2017 at 7:11

2 Answers 2

1

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;
    

    }`

Sign up to request clarification or add additional context in comments.

1 Comment

thanks buddy, i was accessing the token before platform ready
0

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.

2 Comments

One more thing are you able to log response access token?
so you are able to get token. but when you are calling to api; values are not returned, right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.