drh78568 2017-10-23 09:22
浏览 91
已采纳

正确使用JWT和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

  • 写回答

1条回答 默认 最新

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效