Bharat Chauhan
Bharat Chauhan

Reputation: 3322

Property does not exist on type '{}' in Angular2

I have get data using http call. But, i have show above error in compile time.

user.component.ts

this._user.saveUsers(model).then(data => {
    if(data.success==true){
        this.router.navigate(['/user/list']);
    }else{
        console.log("data")
    }
});

Note: my object is dynamic. depends on my http call

Error:

app/users/users.component.ts(33,21): error TS2339: Property 'success' does not exist on type '{}'. app/users/users.component.ts(34,38): error TS2339: Property 'data' does not exist on type '{}'. app/users/users.component.ts(76,25): error TS2339: Property 'success' does not exist on type '{}'.

Upvotes: 2

Views: 7542

Answers (3)

Nahush Farkande
Nahush Farkande

Reputation: 5636

Could you perhaps post the method saveUsers's definition. If you are using es6-promise then take a look at the typings. As you can see the promise class accepts a generic interface T which can be used to define the type of object that can be passed to then. So in case the function saveUsers is returning a promise i.e. something like

function saveUsers(model: any) {
    return new Promise((resolve, reject) => {...})
}

You need to make the function accept a generic and pass it to the returned promise like

function saveUsers<T>(model: any) {
    return new Promise<T>((resolve, reject) => {...})
}

So now what you can simply do is call saveUsers as

saveUsers<{success: boolean}>(model).then(data => {...})

or just pass whatever is the interface of the data being passed to then.

Even if it is not an es6 promise just check the typings of whatever it is you are returning. There will definitely be a way of defining the type of data being passed to then.

UPDATE

To add to micronyks's answer, if you are using something along the lines of axios to execute a network call inside saveUsers the returned response will have this format so in your case it would be data.data.success inside the then block

Upvotes: 1

micronyks
micronyks

Reputation: 55443

If I'm not wrong it should be,

this._user.saveUsers(model).then(data => {
    if(data.data.success==true){                //<<<===changed
        this.router.navigate(['/user/list']);
    }else{
        console.log("data")
    }
});

Upvotes: 0

kit
kit

Reputation: 4920

I don't know about lines 33 and 34 because they are not shown in your code but with 76 you have to put

data: any

Or

data: {success: any}

Upvotes: 5

Related Questions