I have a component that calls a service to fetch some data through HTTP. The service though needs to 'login' at the API if it hasn't before.
So when I call the function getFunnel() from the component I want this function to check if there is session. if no session the func should 'login' to get the token and then run the expected http to return the right observable.
import { Injectable } from '@angular/core';
import { DatePipe } from '@angular/common';
import { Observable } from 'rxjs/Observable';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable()
export class UserService {
public url = "https://example.com";
getFunnel(): Observable<any> {
if(!localStorage.getItem("token")){
this.getToken().subscribe(
response => localStorage.setItem("token", response["token"]),
err => console.log(err),
() => {
return this.http.get(this.url+'/api/funnel', {
headers: {
'authorization': 'JWT '+localStorage.getItem("token")
}
});
}
);
}
else{
return this.http.get(this.url+'/api/funnel', {
headers: {
'authorization': 'JWT '+localStorage.getItem("token")
}
});
}
}
private getToken(){
return this.http.post(this.url+'/api-token-auth/',
{"username": "xxxxx","password": "yyyyy"}
);
}
constructor(private http: HttpClient) { }
}
If not token this will return undefined. How do you solve this kind of situations?
thanks
EDIT:
Ok so I understand I have to use switchMap or some flattening function here. But how? an example would be awesome.
Thanks!