Angular 4 subscribe未返回值
在发出HttpClient post请求后,我正在尝试从Angular 4服务获取数据,我可以看到数据正在subscribe方法中返回,但我无法将其传递给该方法中的其他变量;下面是调用服务的组件的代码: ==========服务方法==============Angular 4 subscribe未返回值,angular,rxjs,Angular,Rxjs,在发出HttpClient post请求后,我正在尝试从Angular 4服务获取数据,我可以看到数据正在subscribe方法中返回,但我无法将其传递给该方法中的其他变量;下面是调用服务的组件的代码: ==========服务方法============== autheticateUser(name: string, pass: string) { const info: any = {}; info.userName = name; info.password = pass;
autheticateUser(name: string, pass: string) {
const info: any = {};
info.userName = name;
info.password = pass;
return this._http.post<Itoken>(this.url, info)
.shareReplay()
.do((data)=> {this.jwtToken = data;});
}
login() {
this.flag = true;
this.mode= 'indeterminate';
this.authuser.autheticateUser(this.user.userName,this.user.password)
.subscribe((data)=> {this.localtoken = data;});
console.log(this.localtoken); // No value this.localtoken variable
.subscribe()是异步的。因此,您不知道它何时会被触发,如果您在subscribe()之外处理结果(如您的console.log()),则可能尚未定义此结果
正如@TheUnreal所说,将您的日志移动到订阅中。这就是您想要使用它的方式:)将日志移动到订阅中。例如,像这样的代码
userResumeBio:any=[]代码>
this.userresumeservice.getResume().subscribe((res: Response) => {
console.log(res , 'User resume response');
this.userResumeBio = res;
console.log(this.userResumeBio , 'UserService userResumeBio response');
}, err=>console.log(err))
在订阅中执行您的console.log
。当前,您正在尝试查看localtoken
中的内容,然后它到达hanks以获取回复:);是的,我可以看到subscribe中的数据,但是我想使用subscribe方法之外的数据。如何从login方法中的subscribe to other变量中获取该值?可能重复@user2741438您能描述一下您想用localtoken做什么吗?我们可以向您建议一种同样的方法。另外,让我告诉你,在subscribe方法之外,在subscribe被调用的方法之内,没有办法使用localtoken。@jornsharpe,我同意你的看法