angular - http post后角度组件如何从服务中获取返回对象?
问题描述
我正在使用angular 4
. 如何从服务中获取返回对象?
export class LoginRequest {
username : string;
password : string;
}
export class LoginResponse {
token : string;
message : string;
status : string;
}
登录组件.ts
export class LoginComponent {
...
loginRes : LoginResponse;
...
login(loginReq : LoginRequest) {
// here how can I get return object
this.loginRes = this.loginService.login(this.loginReq);
}
}
登录服务.ts
export class LoginService {
...
loginRes : LoginResponse;
...
login() {
// here how can I return loginRes object
this.http.post(API_URL + "weblogin", loginReq)
.subscribe(
res => {
this.loginRes = res.json() as LoginResponse;
},
err => {
this.loginRes = new LoginResponse();
this.loginRes.message = "Failed to conntect the server";
this.loginRes.status = "NOT_OK";
this.loginRes;
}
);
}
}
更新
export class LoginComponent implements OnInit {
loginRes : LoginResponse;
login() {
this.loginService.login(this.loginReq).subscribe(
res => {
this.loginRes = res.json() as LoginResponse;
},
err =>{
this.loginRes = new LoginResponse();
this.loginRes.message = "Failed to conntect the server";
this.loginRes.status = "NOT_OK";
}
);
console.log(this.loginRes.message + " Response Data");
}
}
export class LoginService {
login(loginReq : LoginRequest) {
return this.http.post(Constant.API_URL + "weblogin", loginReq);
}
}
解决方案
将您的服务更改为:
export class LoginService {
...
loginRes : LoginResponse;
...
// returning with type here
login(): Observable<LoginResponse> {
return this.http.post(API_URL + "weblogin", loginReq)
}
}
然后在组件中:
export class LoginComponent {
...
loginRes : LoginResponse;
...
login(loginReq : LoginRequest) {
// here how can I get return object
this.loginService.login(this.loginReq)
.subscribe( res => {
// handle "success"/"error" accordingly,
this.loginRes = res;
})
}
}
另外,如果您不直接使用管道,请确保您处于unsubscribing
阶段ngDestroy()
async
更新 1
- 不要只是声明
loginRes : LoginResponse;
,定义loginRes : LoginResponse = new LoginResponse();
。原因是,它是可观察的,它是异步的。因此,尝试在print
不确保其已初始化的情况下会导致undefined
错误 - 使用
console.log(this.loginRes.message + " Response Data");
insidefinally()
作为一个好习惯
推荐阅读
- python - 是否建议使用 if...else 条件来检查键或使用 try...except 在 python 中捕获 KeyError 异常?
- git-flow - 初始化 git 流
- mysql - 需要 Openshift mysql 帮助
- ios - Ionic 3 Platform Ready 仅在应用程序关闭或暂停后触发
- python - 如何在 conftest.py 中设置会话详细信息以获取产量以及 pytest 中的夹具?
- rust - 在 for 循环中处理“借来的值不够长”
- node.js - 使用 POST 请求传递 JSON 数据后无法从 Postman 获得响应响应
- c++ - 为什么互斥锁不能与 2 个线程共享资源一起使用?
- python - 在 Linux 上安装 PyQt5 5.14.1
- android - Android - 从 Firebase 读取数据