I have a project where I am utilizing angular's $http service to fetch data from a remote endpoint. I am keen on incorporating rxjs Observables, hence the call in my service is structured as follows:
userInfo() : Rx.Observable<IUserInfo> {
var url : string = someUrl + this._accessToken;
return Rx.Observable.fromPromise<IUserInfo>( this.$http.get<IUserInfo>( url ) );
}
This method is then subscribed to by my controller as shown below:
getUserInfo() : void {
this._googleService.userInfo().subscribe(
( result ) => { this.handleUserInfo( result ) },
( fault : string ) => this.handleError( fault )
)
}
private handleUserInfo( result : IHttpPromiseCallbackArg<IUserInfo> ) : void {
console.log( "User information received at " + new Date() );
this._name = result.data.given_name + " " + result.data.family_name;
this._email = result.data.email;
this._profilePicUrl = result.data.picture;
}
The issue arises when the name, email, or profile picture fields are updated but not reflected in the view. The changes only become visible after another action triggers an angular $apply. This delay is due to the Observable causing the changes in the controller to occur after the angular digest cycle initiated by the $http call. Interestingly, this problem does not arise if my service simply returns a promise to the controller.
How can I ensure my view gets updated in this scenario? I prefer not to manually connect each observable to trigger a digest loop. Instead, I want all Observables to automatically trigger a digest cycle upon receiving new values or errors.