在http post之后,角度组件如何从服务获得返回对象?

时间:2018-05-18 10:33:38

标签: angular typescript

我正在使用angular 4。如何从服务中获取返回对象?

export class LoginRequest {
  username : string;
  password : string;
}

export class LoginResponse {
  token : string;
  message : string;
  status : string;
}

LoginComponent.ts

export class LoginComponent {
    ...
    loginRes : LoginResponse;
    ...

    login(loginReq : LoginRequest)  {
        // here how can I get return object
        this.loginRes = this.loginService.login(this.loginReq);
    }
}

LoginService.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);
  }   
}   

enter image description here

3 个答案:

答案 0 :(得分:0)

将您的服务更改为:

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");内使用finally()作为良好做法

答案 1 :(得分:0)

http中的serversubscribe发送component个回复

所以,在服务中,只需return api call

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 => {
                console.log(res);
                this.loginRes =  res;
            },  
            err => {
                console.log(err, 'errrrr')
                this.loginRes = new LoginResponse();
                this.loginRes.message = "Failed to conntect the server";
                this.loginRes.status = "NOT_OK";
                this.loginRes;
            }
        );
    }
}

<强>服务

export class LoginService {
    loginRes : LoginResponse;

    login()  {
        return this.http.post(API_URL + "weblogin", loginReq)

    }
}

答案 2 :(得分:0)

如果您使用'@ angular / http':

登录-service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

export class LoginService {

    constructor(private http: Http) {}

    login(credentials) {
        return this.http.post(`API_URL`, credentials)
        .map(res => res.json());
    }
}

如果您使用'@ angular / common / http':

登录-service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map';

export class LoginService {

    constructor(private http: HttpClient) {}

    login(credentials) {
        return this.http.post(`API_URL`, credentials)
        .map(res => res);
    }
}

组件:

登录-component.ts

import { Component } from '@angular/core';
import { LoginService } from './login-service.ts';

@Component({
    ...
})
export class LoginComponent {

    constructor(private loginService: LoginService) {}

    login(loginReq : LoginRequest) {
        this.loginService.login(loginReq)
            .subscribe(res => {
                console.log(res);
            });
    }
}