2
votes

I'm having some problems with Angular 2 http get and route guards.

I'm trying to check if a user is logged in on the guard of a route.

This is the guard file

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return this.checkLogin(state.url);
}

checkLogin(url) {
    if(url == "/login") {
        return !this.service.isLogged()
    }

    if(this.service.isLogged()) {
        return true;
    }

    this.service.redirectURL = url;
    this.router.navigateByUrl('/login');
    return false;
}

the service function isLogged is just this line that calls another service

isLogged() {
    return this.auth.isLogged();
}

And this is the auth service that does the http call

isLogged() {
    let isLogged = new Observable<boolean>(observer => {
        var headers = new Headers();
        headers.append("Content-Type", 'application/json');

        return this.http.get(`${Constants.SERVER_IP}/auth/logged`,{headers: headers})
            .map(res => res.json())
            .map(user => {
                observer.next(true);
                observer.complete();
            })
            .catch(error => {
                observer.next(false);
                observer.complete();
            });
    });

    return isLogged;
}

I get the following error on the .catch call:

Argument of type '(error: any) => void' is not assignable to parameter of type '(err: any, caught: Observable) => ObservableInput'. Type 'void' is not assignable to type 'ObservableInput'.

Just in case it matters, the server is an Express app with the following path:

router.get('/logged', function(req, res, next) {
if(req.session.isLogged && req.session.userID) {
    userBackend.getUserByID(req.session.userID)
        .then(function(user) {
            res.json(user);
        })
        .catch(function(reason) {
            res.status(404).end(reason);
        });
}
else {
    res.status(404).end("User not logged in.");
}
});
1

1 Answers

0
votes

I don't think there is a need to return anything in Observer. Try executing the following:

isLogged() {
    let isLogged = new Observable<boolean>(observer => {
        var headers = new Headers();
        headers.append("Content-Type", 'application/json');
    this.http.get(`${Constants.SERVER_IP}/auth/logged`,{headers: headers})
        .map(res => res.json())
        .map(user => {
            observer.next(true);
            observer.complete();
        })
        .catch(error => {
            observer.next(false);
            observer.complete();
        });
});

return isLogged;
}