Search code examples
jsonionic2

ionic2 Property does not exist on type '{}'


I am getting a json in typescript in ionic framework.
The json is:

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

And I print the data:

console.log("NULRA CHECKING: " + data.result + " " + data.user);

It gives the error:

Typescript Error

Property 'result' does not exist on type '{}'.

Property 'user' does not exist on type '{}'.

auth-service.ts:

login(credentials) {
    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, reject) => {
        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);
        },(err) => {
            reject(err);
        });
    });
}

In login.ts:

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

    });
}

Anyone know how to deal with it? because the json I confirmed have result and user. Thanks a lot.

when console.log(data): enter image description here


Solution

  • Try this-

    public userData: any = {};
    
    doLogin(){
        this.authService.login(this.loginData)
        .then(data => {
            this.userData = data;
            console.log(`NULRA CHECKING: ${this.userData.result} ${this.userData.user}`);
        }
        .catch(err => {
    
        });
    }