我正在运行下面的代码,允许用户登录系统。作为此功能的一部分,正在使用HTTP POST(返回Observable)。由于这是使用JWT,我必须提取TOKEN中的值。
我想以JSON格式将Observable(带有这些TOKEN值)返回给调用程序。我尝试使用地图功能如下:
adminLogin(username, password) {
let url = `${this._apiRoot}/login`;
let tokenResp = {};
this.http.post(url, JSON.stringify({ username: username, password: password }), { observe: 'response' })
.map(response => response.json())
.subscribe((response: HttpResponse<any>) => {
[ ... snip ...]
但我的经验是“订阅”永远不会被调用。
我该怎么办?
TIA
原始代码
adminLogin(username, password) {
let url = `${this._apiRoot}/login`;
let tokenResp = {};
this.http.post(url, JSON.stringify({ username: username, password: password }), { observe: 'response' })
.subscribe((response: HttpResponse<any>) => {
let token = response.headers.get("Authorization");
if (token) {
let t = JWT(token);
console.log("-- what is in the token --");
console.log(t);
// need to set the value here
this.userLoggedIn.next(setUser);
}
},
(error: HttpErrorResponse) => {
if (error.error instanceof Error) {
let errorFound = console.error(error.status + " "
+ error.error.message + " " + error.message );
console.error(errorFound);
return Observable.throw(errorFound);
}
else {
let errorFound = "Server-Side Error has taken place ";
console.error(errorFound);
return Observable.throw(new Error(errorFound));
}
});
}
答案 0 :(得分:1)
如果你想用Token(无论什么类型)返回一个observable,你就不能把你的subscribe方法参数类型作为HttpResponse.I认为你得到了编译错误
试试
adminLogin(username, password) : Observable<JWT> //Assuming this is a type
this.http.post(url, JSON.stringify({ username: username, password: password }), { observe: 'response' })
.map((response: HttpResponse<any>) => {
let token = response.headers.get("Authorization");
if (token) {
let t = JWT(token);
return t;
}
return null; //Or error
},
//Error handling
并且在调用方法
adminLogin(username,password).subscribe((token: JWT )=>
{
//use token
}