Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 cannot access 'this' inside a promise

Tags:

angular

I am unable to call a function inside promise of ng2-sweetalert2 plugin

swal({
    title: 'Are you sure?',
    text: "You won't be able to revert this!",
    type: 'warning',
    showCancelButton: true,
    confirmButtonText: 'Yes, delete it!'
}).then(function(x) {
    this.removeNote(key);
    swal(
    'Deleted!',
    'Your file has been deleted.',
    'success'
    );
}, function(e){
       console.log('Cancelled');
});

removeNote(key){
    this.todo.remove(key);
    this.afService.closeNote(key);
}

this.removeNote() cause error.

EXCEPTION: Uncaught (in promise): TypeError: Cannot read property 'removeNote' of undefined

How do I overcome this? I used NgZone but i get the same error

like image 546
Ashik Basheer Avatar asked Mar 05 '17 09:03

Ashik Basheer


People also ask

How to work with Promises Angular?

How To Create Promises in Angular? To create a promise in Angular we just need to use 'new Promise(function)' syntax. The promise constructor takes function as a parameter and that inner function takes resolve and reject as a params.

Why use Promise in Angular?

A promise is a placeholder for a future value. It serves the same function as callbacks but has a nicer syntax and makes it easier to handle errors.

What is Promise in Angular 10?

A promise is a JavaScript/TypeScript object that may produce a value at some point in time. A promise may be in one of 4 possible states: fulfilled, rejected, pending or settled. A promise can be: fulfilled - The action relating to the promise succeeded.

What are the features of Promises in Angular?

Promises deal with one asynchronous event at a time, while observables handle a sequence of asynchronous events over a period of time. Emit multiple values over a period of time. Emit a single value at a time. Are lazy: they're not executed until we subscribe to them using the subscribe() method.


1 Answers

Assuming you're using TypeScript, you could use the arrow function expression, which preserves the value of this.

swal({...}).then((x) => console.log(this)); // now 'this' is your component
like image 175
Brother Woodrow Avatar answered Oct 02 '22 15:10

Brother Woodrow