angular - why return type Observable is better than primitive type? -
i started implement application in angular 2. have questions codes below. why return observable instead of boolean type in authenticate method? if around source codes experts, return of them observable. afraid might stupid question, curious it.
authenticate(user: string, pass: string): observable<boolean> { return this.http.request(new request({ method: requestmethod.post, url: this.baseurl + "login", body: { name: user, password: pass } })).map(response => { let r = response.json(); this.auth_token = r.success ? r.token : null; return r.success; }); }
you'll notice in methods http request, return observables.
that because http requests (network) request inherently asynchronous. meaning, when make network request, dont know when in call stack should handle response. response dependent on network speed, api efficiency, interference, etc..
why observables? subscribed to! subscribe them when response comes through. rxjs comes whole bunch of operators make parsing of responses, or there errors, cleaner , more pleasant experience.
i recommend going through rxjs examples found online. observables super powerful. can manage state of app, data access layer, view, , in between.
check rxjs site documentation , visuals on rx. http://reactivex.io/
Comments
Post a Comment