angular - How can I "monkey patch" an Observable for Zone.js? -
i'm creating angular 2 component, , angular's change detection isn't working me when using observable pattern. looks this:
let getresult$ = this.http.get('/api/identity-settings'); let manager$ = getresult$ .map((response) => /* -- create manager object -- */); let signinresponse$ = manager$ .flatmap(manager => manager.processsigninresponse()); this.readytologin$ = manager$.map(() => true).startwith(false); this.isloggedin$ = signinresponse$.map(() => true).startwith(false);
then in template:
<h1>ready log in: {{readytologin$ | async}}</h1> <h1>logged in: {{isloggedin$ | async}}</h1>
since readytologin$
observable based on synchronous set of operations happen in response http.get()
(which angular "monkey patches" ensure knows when needs detect changes), "ready log in" message switches true
@ appropriate time.
however, since processsigninresponse()
produces promise<>
, subscribing result of flatmap
occurring asynchronously http request's completion event. therefore, requires manual intervention notify component's zone needs check changes.
how can wrap signinresponse$
observable in way ngzone
knows detect changes after subscriptions have been resolved?
update
brandon's answer worked until updated rc5, @ point things stopped working again. turns out the 3rd-party library using borked zone.js. once resolved, there no need use workaround @ all--the built-in monkey patching worked!
you can make new observeonzone
operator can used "monkey patch" observable. like:
rx.observable.prototype.observeonzone = function (zone) { return observable.create(observer => { var onnext = (value) => zone.run(() => observer.next(value)); var onerror = (e) => zone.run(() => observer.error(e)); var oncomplete = () => zone.run(() => observer.complete()); return this.subscribe(onnext, onerror, oncomplete); }); };
and use so:
this.isloggedin$ = signinresponse$.map(() => true).startwith(false).observeonzone(zone);