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条回答 默认 最新

报告相同问题?

悬赏问题

  • ¥30 matlab appdesigner私有函数嵌套整合
  • ¥15 给我一个openharmony跑通webrtc实现视频会议的简单demo项目,sdk为12
  • ¥15 vb6.0使用jmail接收smtp邮件并另存附件到D盘
  • ¥30 vb net 使用 sendMessage 如何输入鼠标坐标
  • ¥15 关于freesurfer使用freeview可视化的问题
  • ¥100 谁能在荣耀自带系统MagicOS版本下,隐藏手机桌面图标?
  • ¥15 求SC-LIWC词典!
  • ¥20 有关esp8266连接阿里云
  • ¥15 C# 调用Bartender打印机打印
  • ¥15 我这个代码哪里有问题 acm 平台上显示错误 90%,我自己运行好像没什么问题