Ionic 2获得RESTful API问题

时间:2017-07-21 13:29:52

标签: rest api ionic2

我正在获取一个RESTful API,我对获取JSON有一些疑问,这是我得到的JSON:

{
    "result": "success",
    "user": {
        "loggedIn": true,
        "name": "Nulra",
        "password": ""
    }
}

以及在auth-service.ts中获取JSON的部分:

login(credentials) {

    if(this.data){
        return Promise.resolve(this.data);
    }

    let opt: RequestOptions;
    let myHeaders: Headers = new Headers;

    myHeaders.set('Accept', 'application/json; charset=utf-8');
    myHeaders.append('Content-type', 'application/json; charset=utf-8');
    opt = new RequestOptions({
        headers: myHeaders
    })

    return new Promise(resolve => {
        this.http.get(apiUrl+'login/0/login?email='+credentials.email+'&password='+credentials.password, opt)
        .map(res => res.json())
        .subscribe(data => {
            this.data = data;
            resolve(this.data);
        });
    });

在我的login.ts中:

doLogin() {
    this.authService.login(this.loginData).then(data => {
        console.log("NULRA CHECKING: ",data);
    }, (err) => {

    });
}

我发现它只是让用户参与JSON,并且在我在控制台日志中检查时错过了JSON中的结果部分。如何获得结果和用户部分?

控制台日志:

Object {loggedIn: true, name: "Nulra", password: ""}

1 个答案:

答案 0 :(得分:0)

尝试从json获取REST-API对象的此解决方案,请检查

控制台中输出

console.log("NULRA CHECKING: " + JSON.stringify(data));

<强> login.ts:

doLogin() {
    this.authService.login(this.loginData).subscribe( (data) => {
        console.log("NULRA CHECKING: " + JSON.stringify(data));
    }, (error) => {
        console.log("Error : " + error);
    });
}

<强> AUTH-service.ts:

login(credentials): Observable<any> {

    let opt: RequestOptions;
    let myHeaders: Headers = new Headers;

    myHeaders.set('Accept', 'application/json; charset=utf-8');
    myHeaders.append('Content-type', 'application/json; charset=utf-8');
    opt = new RequestOptions({
        headers: myHeaders
    })

    return this.http.get(apiUrl + 'login/0/login?email=' + credentials.email + '&password=' + credentials.password, opt)
        .map((res: Response) => res.json());
}