从http post Angular返回响应



我想从post-method中获取一个响应,并在subscribe方法中使用这个值。在评论中,我还写了关于我的问题的信息。

我的代码

login(): void {
this.authService.login(this.model)
.subscribe(next => {
//here I wanted to use received value
this.alertifyService.success('success');
}, error => {
this.alertifyService.error('error');
}
);
}

login(model: any) {
return this.http.post(this.baseUrl + 'login', model)
.pipe(map((response: any) => {
// how to send this reponse to my subscribe method ?
const user = response;
if (user) {
localStorage.setItem('token', user.token);
this.decodedToken = this.jwtHelper.decodeToken(user.token);
console.log(this.decodedToken);
}
}
));
}

您只需要从map返回值

login(model: any) {
return this.http.post(this.baseUrl + 'login', model)
.pipe(map((response: any) => {
const user = response;
if (user) {
localStorage.setItem('token', user.token);
this.decodedToken = this.jwtHelper.decodeToken(user.token);
return this.decodedToken;
}
}
));
}

然后像这样使用:

authService.login(/**/).subscribe(token => /*do something with the token*/)

最新更新