Angular Chain Http Request
I created a service where I wrapped all my HTTP requests (get, put, post...).
get(url) {
const headers = new Headers();
this.sessionToken(headers); // just add the headers...
return this.http.get(url, {
headers: headers
});
}
How can I perform a method before the (eg.) GET request is sent?
In my scenario, I have a method that returns me back a token and this token need to be saved on the localStorage and, following the chain, appended to the headers!
initClient() {
return this.http.post('/connect/', {})
.map(res => res.json())
}
How can I conditionally insert this request before the Http call is done?
Directly in this Service and not going to subscribe on each HTTP calls.
Here what I tried to do:
get(url) {
if (!localStorage.getItem('token')) {
this.initClient()
.subscribe(session => {
localStorage.setItem('token', JSON.stringify(session));
});
}
const headers = new Headers();
this.sessionToken(headers);
return this.http.get(url, {
headers: headers
});
}
But the HTTP request is solved before of the initClient() is called!
What I need to do?
- A method returns an Http request
- Before the request is sent Get Token / Set Token localStorage
- Continue Http request including the Token in the Headers
Possible Solution - Error:
@CozyAzure - Answer
Argument of type '(session: any) => void' is not assignable to parameter of type '(value: any, index: number) => ObservableInput<{}>'.
Type 'void' is not assignable to type 'ObservableInput<{}>'.
Trying to set initClient() { ...} to be of type "any":
initClient(): any { ... } the previous error disappear, but another error comes out:
ERROR TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.