在Angular 2中将Promise对象转换为JSON

时间:2017-02-27 22:25:12

标签: json angular angular2-http

我尝试进行HTTP POST,然后检查响应是否失败或成功。

HTTP调用如下所示:

doLogin(credentials) {
    var header = new Headers();
    header.append('Content-Type', 'application/x-www-form-urlencoded');
    var body = 'username=' + credentials.username + '&password=' + credentials.password;
    return new Promise((resolve, reject) => {
        this.http.post(this.url, body, {
            headers: header
        })
            .subscribe(
                data => {
                    resolve(data.json());
                },
                error => {
                    resolve(error.json());
                }
            );
    });

}

此功能的调用如下:

data: Object;
errorMessage: Object;

login($event, username, password) {
    this.credentials = {
        username: username,
        password: password
    };

    this._loginService.doLogin(this.credentials).then(
        result => {
            this.data = result;
            console.log(this.data);
        },
        error => {
            this.errorMessage = <any>error;
            console.log(this.errorMessage);
        });
}

在Chrome控制台上,数据如下:

Object {status: "Login success", token: "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJjcmlzdGkiLCJ1c2VyS…blf1AzZ6KzRWQFNGXCrIeUHRG3Wrk7ZfCou135WmbVa15iYTA"}

如何访问Angular 2中的状态?因为如果我试图访问this.data.status,它就无法使用。

我应该创建一个具有状态和令牌属性的类吗?

2 个答案:

答案 0 :(得分:0)

你可以这样做:

data: Object;
errorMessage: Object;

login($event, username, password) {
    this.credentials = {
        username: username,
        password: password
    };

    this._loginService.doLogin(this.credentials).then(
        (result: any) => {
            this.data = result;
            console.log(this.data);
            console.log(this.data.status);
        },
        error => {
            this.errorMessage = <any>error;
            console.log(this.errorMessage);
        });
}

result设置为输入任意内容。这样您就可以访问status了,但是如果您在class内创建rxjs/map并使用service来填充class所以欲望。

答案 1 :(得分:0)

要回答您的问题,您可以使用http中的observable订阅中可用的response.ok布尔值。

因此,根据您的代码,您可以将data对象直接传递给promise并在解析data.ok之前检查data.json

//...
return new Promise((resolve, reject) => {
    this.http.post(this.url, body, {
        headers: header
    })
        .subscribe(resolve,
         error => {
                reject(error.json());
            }
        );
});

// then you would have something like this:

this._loginService.doLogin(this.credentials).then(
    result => {
        if (result.ok) {
            this.data = result;
            console.log(this.data);
        }
    },
    error => {
        this.errorMessage = <any>error;
        console.log(this.errorMessage);
    })

<强> SUGGESTION

现在,我建议摆脱承诺,因为我相信你并不真的需要它。无论谁使用你的服务,都可以订阅http帖子返回的observable,如下所示:

doLogin(credentials) {
    let header = new Headers();
    header.append('Content-Type', 'application/x-www-form-urlencoded');
    var body = 'username='+credentials.username+'&password='+credentials.password;
    return this.http.post(this.url, body, { headers: header });
}

然后,登录时:

login($event, username, password) {
    this.credentials = {
        username: username,
        password: password
    };

    this._loginService.doLogin(this.credentials).subscribe(response => {
        if (response.ok) { // <== CHECK Response status
            this.data = response.json();
            console.log(this.data);
        } else {
            // handle bad request
        }
    },
    error => {
        this.errorMessage = <any>error;
        console.log(this.errorMessage);
    });
}

希望这有帮助!