0
votes

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!

1
One possible solution could be the Http Interceptors, take a look at this link, ryanchenkie.com/… - Daniel C.
Chain obs using switchMap or the like - Harry Ninh
@Alejandro, the "magic answer" is replace this.getToken().subscribe(...) by this.getToken().switchMap(...). A brief explain: You don't subscribe to getToken and then make a request about the http. You make a request to getToken but, when you have the response change (switch) this response with the response of a new request - Eliseo
@Eliseo could you give me an example of the code please? I get switchMap does not exist on type Observable - Alejandro
@Alejandro you must import the operator: import 'rxjs/add/operator/switchMap'; - Eliseo

1 Answers

0
votes

Hello you will always return undefined in your case as you are not subscribing to the post. So try to read about http post subscribe or map to wait and process your data before returning it :) Example here https://www.metaltoad.com/blog/angular-2-using-http-service-write-data-api