Cacoon
Cacoon

Reputation: 2538

Properly use JWT with Angular 2

I have a working backend JWT setup on my PHP server, and I have finally after many hours gotten a result to log in console for angular, what I cant figure out now is how to manage this result and wait for the information to load to return a result, if I remove my subscribe function I cannot even render results which confuses me, Why cannot I simply use map?

Anyway here is my login function:

login(username: string, password: string): Observable<boolean> {
        let result = false;
        var postData = "email=" + username + "&password=" + password;
        let headers: Headers;
        headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');

        this.http.post('https://callum.tech/jwt/', postData, {headers: headers})
            .take(1)
            .map((res:any) => res.json())
            .subscribe(
                data => {
                    console.log(data.token)
                    if (data.token) {
                        console.log("token exists");
                        // set token property
                        this.token = data.token;

                        // store username and jwt token in local storage to keep user logged in between page refreshes
                        localStorage.setItem('currentUser', JSON.stringify({ username: username, token: data.token }));
                        result = true;
                    }
                },
                err => {console.log(err)}
                //,() => console.log("done!?")
            );
        console.log(result);
        return Observable.of(result);
    }

Now this will login with the correct information (I return a json in PHP under 'token' and there are no issues, this is shown in the console)

enter image description here

I am not sure how to wait, and get the proper response, the POST stuff seems to be really sensitive to having subscription etc or it wont post data, so I am not sure how to deal with this

Upvotes: 0

Views: 138

Answers (1)

Martin Ad&#225;mek
Martin Ad&#225;mek

Reputation: 18429

Observable.map just maps the resolved response, it will not start the request. You always need to use subscribe to start it. That's the way how observables work.

Also the code is asynchronous, you can not do the console.log(result); at the end of your snippet, that line will be ran immediately after creating the observable via this.http.post()....

See the docs for more information:

https://angular.io/guide/http

https://xgrommx.github.io/rx-book/content/getting_started_with_rxjs/creating_and_querying_observable_sequences/creating_and_subscribing_to_simple_observable_sequences.html

https://scotch.io/tutorials/angular-2-http-requests-with-observables

Upvotes: 1

Related Questions