angularjs - 打字稿:在 Observable 之外获取数据
问题描述
我试图在 Typescript 中发送一个 HttpRequest。我需要将收到的数据存储在订阅功能之外。但是当我想在订阅之外打印用户变量时,它是undefined
. 在订阅功能中它工作正常。那么我如何才能访问订阅功能之外的数据呢?
private user: User;
public sendHttpLogin(username: string, password: string) {
this.http.get<User>('http://localhost:8080/login?password='+password+'&username='+username).subscribe(data => {
//save the data on a User Object
this.user = data;
//this works fine
console.log(this.user)
});
//this is undefined
console.log(this.user);
}
解决方案
第二个在返回console.log
之前被调用http.get
,所以这就是它未定义的原因。
您的第一个console.log
是正确的,您只能使用从get
函数返回的数据。
您可以在那里调用另一个函数来继续您的应用程序的流程。
private user: User;
public sendHttpLogin(username: string, password: string) {
this.http.get<User>('http://localhost:8080/login?password='+password+'&username='+username).subscribe(data => {
this.continueApp(data)
})
}
private continueApp(data){
this.user = data
}
推荐阅读
- javascript - 如何在 setInterval 函数中访问 SVG 数据属性
- java - Akka 不加载 application.conf
- javascript - 使用 EaselJS,如何在不重绘现有位图元素的情况下为绘画设置帧速率?
- spring-boot - 尝试使用 Postman 访问 SpringBoot 控制器但没有成功
- javascript - 可重用的 bcrypt 函数,从函数问题返回数据
- azure - Azure IOT 集线器预配错误:AMQP 传输异常 IotHubUnauthorizedAccess 401002
- mule - 检查 XML 元素是否具有 xsi:nil="true"
- c - C中的逆向工程;炸弹实验室
- javascript - 计算结果为 html
- reactjs - Firebase Google 身份验证未显示电子邮件地址