import { IScope } from 'angular' ; import * as Rx from 'rxjs' ; import { AngularHttpError } from '../notify/lib' ; type FatalErrorFn = ( error : AngularHttpError | Error | string , location ? : string ) => void ; function callInDigest ( $scope , fn , fatalError ? ) { try { if ( $scope . $root . $$phase ) { fn ( ) ; } else { $scope . $apply ( ( ) => fn ( ) ) ; } } catch ( error ) { if ( fatalError ) { fatalError ( error ) ; } } } /**
 * Subscribe to an observable at a $scope, ensuring that the digest cycle
 * is run for subscriber hooks and routing errors to fatalError if not handled.
 */ export function subscribeWithScope < T > ( $scope , observable , observer ? , fatalError ? ) { return observable . subscribe ( { next ( value ) { if ( observer && observer . next ) { callInDigest ( $scope , ( ) => observer . next ! ( value ) , fatalError ) ; } } , error ( error ) { callInDigest ( $scope , ( ) => { if ( observer && observer . error ) { observer . error ( error ) ; } else { throw new Error ( `Uncaught error in subscribeWithScope(): ${ error ? error . stack || error . message : error }` ) ; } } , fatalError ) ; } , complete ( ) { if ( observer && observer . complete ) { callInDigest ( $scope , ( ) => observer . complete ! ( ) , fatalError ) ; } } , } ) ; }