I have a function being used in my service that is defined as:
var getData = function() {
return anotherService.getData().$promise;
};
and a this
property that I manipulate throughout the service.
this.someProperty = 'a string';
I call the above function inside the return section of my service:
return{
updateProperty: function(){
getData().then(function(data){
this.someProperty = data;
});
}
}
In the above, I get an this is undefined
related error in my browser console. I assume this is because the resolved $promise
is an AJAX call and this
is used out of context. What's the best way to manipulate a this
property using the returned data from an AJAX call in this instance?
Declare getPosts () custom function inside this function use Promise to fetch the posts data. We declared the promise instance in the Angular custom method with new keyword and passed the resolve and reject method in it. We set up the apiURL in the getPosts function and made the Http Get request followed by the toPromise () method.
You don’t have to do anything else for the span, but for the b-comp you need to indicate that it receives textContent property: Now, whenever the AText property changes on the A component Angular will automatically update the property textContent on B component and span. It will also call ngOnChanges lifecycle hook for the child component.
Open your Angular project in your favorite code editor and then go to app.module.ts file and import HttpClientModule service. Then also register it inside the imports array. Next, go to app.component.ts file. Here we will write the core logic to make the HTTP GET request and manage the response using the ES6 Promise in Angular.
Angular 11 Promises Example with HttpClient API. In this section, we are going to look at how to use Promises in Angular to manage the HTTP response asynchronously. Open your Angular project in your favorite code editor and then go to app.module.ts file and import HttpClientModule service. Then also register it inside the imports array.
if you're manipulating this
throughout your service, assign it to a variable like var self = this
. The problem is that this
is the context of a function and can be changed by other code using fn.call(context)
or fn.apply(context, args)
. So it's liable to be different inside of the scope of any given function.
So just assign it to some variable and use it:
var self = this;
return {
updateProperty: function(){
getData().then(function(data){
self.someProperty = data;
});
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With