Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - 'then' does not exist on type 'void'

I try simple app where I delete user after clicking on delete button.

When I try to run server like this I get error on then in deleteUser() component:

 deleteUser(user: User, event: any) {
    event.stopPropagation();
    this.userService
      .deleteUser(user)
      .then(res => {
        this.httpUsers = this.httpUsers.filter(h => h !== user);
        if (this.selectedUser === user) { this.selectedUser = null; }
      })
      .catch(error => this.error = error);
  }

service:

  deleteUser(user: User) {
    console.log('Deleting user');
  }

Error message:

app/users.component.ts(46,8): error TS2339: Property 'then' does not exist on type 'void'.

Line 46 from error is one above with .then(res => {

While googling I found this question so I removed void from deleteUser function, however nothing changed.

Any hint what I'm doing wrong?

like image 425
Andurit Avatar asked Aug 24 '16 14:08

Andurit


People also ask

Does not exist on type () => void?

The "Property does not exist on type void" error occurs when we try to access a property on the return value of a function that doesn't return anything. To solve the error, make sure to return the correct value from all of the function's code paths. Copied!

Does not exist on type TypeScript?

The "Property does not exist on type '{}'" error occurs when we try to access or set a property that is not contained in the object's type. To solve the error, type the object properties explicitly or use a type with variable key names. Copied!

Does not exist on type string?

The "Property does not exist on type String" error occurs when we try to access a property that does not exist on the string type. To solve the error, use an object instead of a string, or make sure you're accessing a valid built-in method on the string.


2 Answers

you have to call the delete method so it will return the promise and you can use .then( you have to do like this

deleteUser(user: User) {
   return this.http.delete(url+id,...).toPromise();
}
like image 151
rashfmnb Avatar answered Oct 02 '22 15:10

rashfmnb


You could use then if you are returning a promise. You can use subscribe if you are calling a REST API and then mapping the result

Using then

Service method

  getAudits() {
    // console.log('audits' + amplify.store('audits'));
    let audits: Audit[] = amplify.store('audits'));    
    return Promise.resolve(audits);
  }

Component

this.auditService.getAudits().then(audits => {
  this.audits = audits;
  this.updateChart(true);
});

Using subscribe

Service method

  getAudits() {
    return this.http.get('/rest/batch').map(res => res.json());
  }

Component

this.auditService.getAudits().subscribe(audits => {
  this.audits = audits;
  this.updateChart(true);
});
like image 20
Sacky San Avatar answered Oct 02 '22 17:10

Sacky San