Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Angular Basics Services in Angular Dependency Injection

Constructor args and promises

I am new to constructor, as I cannot understand when Andrew passed Http:http into the constructor like

constructor(http:Http){

}

and also I am not familiar with promises, does Treehouse have a course which teaches javascript promises?

1 Answer

Daniel H.J. Chen
Daniel H.J. Chen
12,888 Points

What this line does is that when the component is initiated, the constructor function creates a private variable "http" which is of type "Http", the service class just imported from '@angular/http'. Then, "http" and its methods like "get" and "post" can be accessed in the component.

Promise is like an event listener for a functional call. You set a promise so that when the functional call finishes executing, the promise evaluates whether the functional call is successful, then send the processing to either the success callback (fulfilled) or failure callback (rejected). The Angular Http calls are Observables, which you convert to Promises and pass the response to appropriate callbacks. You can look up Promises in the following link: https://developers.google.com/web/fundamentals/getting-started/primers/promises

Cool, this bring me to ask what are Observables?

Daniel H.J. Chen
Daniel H.J. Chen
12,888 Points

An Observable is very similar to a Promise as they are both abstract layer for asynchronous calls, except that you have more flexibility. As of ES6, you cannot cancel a Promise - it will always result in success or failure and call the respective callbacks. For Observables, you can cancel via subscriptions and call retries easily. Check more at https://stackoverflow.com/questions/37364973/angular-promise-vs-observable