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

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵