Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在http post之后,angular组件如何从服务获取返回对象?_Angular_Typescript - Fatal编程技术网

在http post之后,angular组件如何从服务获取返回对象?

在http post之后,angular组件如何从服务获取返回对象?,angular,typescript,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 { ...

我使用的是
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);
    }
}
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);
            });
    }
}
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);
  }   
}   

将您的服务更改为:

export class LoginService {
...
loginRes : LoginResponse;
...
 // returning with type here
 login(): Observable<LoginResponse>  {
    return this.http.post(API_URL + "weblogin", loginReq)
 }
} 
此外,如果您没有直接使用
async
管道,请确保在
ngDestroy()
阶段取消订阅

更新1
  • 不要只声明
    loginRes:LoginResponse
    ,定义
    loginRes:LoginResponse=new LoginResponse()。原因是,它是可观察的,它是异步的。因此,在不确保其已初始化的情况下尝试
    打印
    ,将导致
    未定义
    错误
  • 使用
    console.log(this.loginRes.message+“响应数据”)内部
    finally()
    作为一种良好的实践

  • 服务器发送
    http
    响应,并在
    组件中订阅

    因此,在服务中,只需
    返回api调用

    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)
    
        }
    }
    
    服务:

    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)
    
        }
    }
    

    如果使用“@angular/http”:

    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)
    
        }
    }
    
    login-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());
        }
    }
    
    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);
        }
    }
    

    如果使用“@angular/common/http”:

    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)
    
        }
    }
    
    login-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());
        }
    }
    
    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);
        }
    }
    
    组件:

    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)
    
        }
    }
    
    login-component.ts

    export class LoginComponent {
        ...
        loginRes : LoginResponse;
        ...
    
        login(loginReq : LoginRequest)  {
            // here how can I get return object
            this.loginRes = this.loginService.login(this.loginReq);
        }
    }
    
    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);
                });
        }
    }
    

    您应该返回您的http
    返回此.http.post….
    @ochs.tobi如果我这样做,调用方方法没有获取我所需的对象“loginRes”。在组件中订阅,而不是在服务中订阅。然后它也会工作,你不再需要Angular 4
    httpClient中的
    .json()
    ,你得到你想要的了吗?我已经试过了,我在console.log(this.loginRes.message+“响应数据”)中得到了错误;类似于未定义的this.loginRes=res的“无法读取属性”消息
    I添加了一个
    console.log
    请查看应答删除
    console.log(this.loginRes.message+“响应数据”)
    并发送您得到的
    console.log
    ,我还错误地添加了
    console
    ,如果出现任何情况,则在login()中出现编译错误:Observable{返回this.http.post(API_URL+“weblogin”,loginReq)}@CycDemo:错误是什么?我认为这肯定不会是一个重大的问题。分享错误/屏幕截图,我将see@CycDemo:您如何在组件中声明此.loginRes
    。另外,是
    console.log(this.loginRes.message+“响应数据”)在第34行?