【问题标题】:Angular 2 HTTP Post: Cannot get and use response objectAngular 2 HTTP Post:无法获取和使用响应对象
【发布时间】:2016-10-28 01:58:22
【问题描述】:

我目前正在开发一个使用 RESTful 作为后端的 Angular 2 项目。

这里有一个简短的场景,可以帮助我提出我的问题。

当用户登录时,我想重定向到显示一些用户详细信息的个人资料/订单页面。

为了实现这一点,我有一个 Register.ts 在这里我的代码看起来像这样。

export class RegisterService{
    public isLoggedIn:boolean;
    public userDetails:any;
    public newUser = new User("","","",null);

    constructor(private _http: Http){
        this.isLoggedIn = false;
    }


    Register(data:any) {
        const body = JSON.stringify(data);
        // console.log(data);
        this.userDetails = data;
        // console.log("userdets: "+this.userDetails.username);
        const headers = new Headers();
        headers.append('Content-Type', 'application/json');
        return this._http.post(`http://192.168.20.17:8080/webshop/api/user/create?username=`+data.username+`&password=`
                                +data.password+`&email=`+data.email+`&city=`+data.city+`&housenumber=`+data.housenumber+
                                `&street=`+data.street, body, {headers: headers}
        );
    }
Login(data:any):Observable<any>{
        const body = JSON.stringify(data);
        // console.log(data);
        const headers = new Headers();
        headers.append('Content-Type', 'application/json');
        return this._http.post(`http://192.168.20.17:8080/webshop/api/user/login?username=`
            +data.username+`&password=`+data.password, body,{headers:headers})
            .map((res:Response)=> JSON.stringify(res));
        // console.log(this.newUser);

    }

然后在我的 sign-in.component.ts 中,我有使用该服务的方法,如下所示

  onLogin(_username:string, _password:string)
    {
        const data = {
            username:_username,
            password:_password,
            }

        this._registerService.Login(data)
            .subscribe(
                data=> resolve(data.json())
            )
        console.log(this.response);}
onPost(username:string, email:string, password:string, housenumber:string, street:string, city:string)
{
    const data = {
        username:username,
        email:email,
        password:password,
        housenumber:housenumber,
        street:street,
        city:city
    }
    if (data == null)
      this.isValid == false;

    else {
        this.isValid == true;
        this._registerService.Register(data).subscribe(
            data=> this.response = JSON.stringify(data),
            error => console.log(error)),
            data=>console.log(data);
            localStorage.setItem('user', JSON.stringify(data)
            );

        if(localStorage.getItem("user") != null) {
            this._registerService.isLoggedIn = true;
            this._router.navigate(['/order']);
        }
        else
        //replace this with a page
            alert("Sign in with a correct name!");

    }
}

我可以在用户注册时显示用户的详细信息,但是当用户登录时,我无法获得响应,该响应应该是这样的 JSON 对象:

{
  "address": {
    "addition": null,
    "city": "Nijmegen",
    "housenumber": "908",
    "street": "de Voorstenkamp"
  },
  "email": "ernestina_a@ive.com",
  "password": "678",
  "username": "feedme"
}

我尝试创建两个类,User.ts

import {Address} from "./Address.ts";
export class User {
    username:string;
    email:string;
    password:string;
    address:Address;

    constructor(username:string, email:string, password:string,address:Address){
        this.username = username;
        this.email = email;
        this.password = password;
        this.address = address;
    }

    public static createEmptyUser():User{
        return new User("","","",null);
    }
}

还有地址.ts

export class Address {
    street:string;
    housenumber:string;
    addition:string;
    city:string;


    constructor(street:string, housenumber:string,addition:string,city:string) {
        this.street = street;
        this.housenumber = housenumber;
        this.addition = addition;
        this.city = city;
    }

    public static createEmptyAddress():Address {
        return new Address("","","","");
    }

}

使用这两个类,我尝试解析响应以获取用户对象,但我根本无法获得任何响应。

这里有人可以帮我吗?我会很感激的。

【问题讨论】:

    标签: typescript angular


    【解决方案1】:

    您好,我只是展示一个如何从任何 http 响应中获取正文部分的示例:

    getMemberList(){
          this.teamService.getMemberList().subscribe(
            (res)=>{
                      console.log("getMemberList: ",res.json());
            },
            (err)=>{
                      console.log(err);
            }
          )
      }
    

    在上面的代码中,我在 teamService.ts 中调用了一个 HTTP POST 请求。因此,在收到任何 API 的响应后,您必须执行 res.json 才能从响应中获取正文部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-22
      • 2018-09-14
      • 1970-01-01
      相关资源
      最近更新 更多