首页 > 解决方案 > 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);
  }   
}   

在此处输入图像描述

标签: angulartypescript

解决方案


将您的服务更改为:

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

  1. 不要只是声明loginRes : LoginResponse;,定义loginRes : LoginResponse = new LoginResponse();。原因是,它是可观察的,它是异步的。因此,尝试在print不确保其已初始化的情况下会导致undefined错误
  2. 使用console.log(this.loginRes.message + " Response Data");insidefinally()作为一个好习惯

推荐阅读