Example #1
0
  ngOnInit() {
    // Exercise the flow where a state change results in a new action.
    this.search$.subscribe(keyword => {
      if (keyword != '') {
        this.actions.fetchResultDispatch(keyword.length)
      }
    });

    // Exercise the flow where you set a member on change manually instead of
    // using async pipe.
    this.numChars$.subscribe(state => {
      this.numChars = state;
    });
  }
Example #2
0
    constructor(public af: AngularFire, private zone: NgZone, private router : Router) {
        
        this.userData = this.af.auth.flatMap( authState => {
            // Overcome angularfire's zone smashing
            return zone.run((): Observable<any> => {
                if(authState) {
                    this.updatableUser = af.database.object('/users/'+authState.uid);
                    return this.updatableUser;
                } else {
                    this.updatableUser = null;
                    return Observable.of(null);
                    
                }
                
            });
            
        }).cache(1);

        // Detect missing user data and forward to quick-profile
        this.userData.subscribe( authState => {
            if(authState != null && !authState.name) {
                this.router.navigate(['/profile-short']);
            }
        });
       
       // isAdmin should be an observable that sends trues of falses as the users gains or loses admin access
       // Need to combine two streams. take the stream of auth data, and use it to generate a stream of values
       // for the /admin/[userid] and then check to see if the user is an admin
        this.isAdmin =  this.af.auth.switchMap( authState => {
            // Overcome angularfire's zone smashing
            return zone.run((): Observable<boolean> => {
                if(!authState) {
                    return Observable.of(false);
                } else {
                    return this.af.database.object('/admin/'+authState.uid)
                    .catch((a, b) => {
                        // This permission error means we aren't an admin
                        return Observable.of(false)
                    });
                }
            });
        }).map( adminObject => 
             (adminObject && adminObject['$value'] === true)
        ).cache(1);
        
        this.isUser =  this.af.auth.map( authState => !!authState).cache(1);
        
        this.uid = this.af.auth.switchMap( authState => {
            if(!authState) {
                return Observable.of(null);
            } else {
                return Observable.of(authState.uid);
            }
        }).cache(1);

        
        
        
    }
Example #3
0
    inc(){
        this.store.dispatch({type: INCREMENT});

        console.log('counter$', this.counter$);                             // object
        console.log('counter', this.counter$.destination._value.counter);   // value
        console.log('store: ', this.store._value.counter);                  // same value
        this.counter$.subscribe(state => console.log('subscribe: ', state));// proper way
    }
 return new Observable(observer => {
       this.txnDetail$.subscribe(dtl => {
          if(dtl.txnDtl.isLoadingSuccess){
            observer.next(dtl);
            observer.complete();
          }
      })
 });
Example #5
0
 public getDbs() {
     this.dbConn.subscribe((v: DbConnModel) => {
         this.dbRepository.getDbs(v).subscribe((value: Response) => {
             this.store.dispatch(this.dbActions.addDbs(value.json()))
             this.proxyService.notifyDbs(value.json());
         });
     });
 }
  constructor(private appStore: AppStoreService, private utils: UtilsService) {
    this.items$ = this.appStore.items.items$;
    this.appStore.items.selectedItem$
      .subscribe((res) => this.selectedItem = res);

    this.items$.subscribe(res => {
      console.log('items', res);
    });
  }
 ngOnInit(): void {
   this.pokemon$ =  this.store.select<Pokemon>("pokemon", "selectedItem");
   this.error$ =  this.store.select<any>("pokemon", "error");
   // TODO: fix template to use async
   this.sub = this.pokemon$.subscribe( (pokemon: Pokemon) => {
       this.pokemon = pokemon;
   });
   const id = this.route.snapshot.params["id"];
   this.store.dispatch(this.pokemonActions.getDetail(id));
 }
Example #8
0
export function nextFrom<T>(op: Observable<T>): T | undefined {

    let result: T | undefined = undefined;

    op.subscribe(res => result = res);

    tick();

    return result;
}
  ngAfterViewInit() {
    this.lamps$.subscribe(lamps => {
      lamps.forEach(lamp => {
        const lampDirective = this.findLamp(lamp.id);
        if (lampDirective) {
          lampDirective.changeColor(lamp.color);
        }
      });
    });

    this.services$.subscribe(services => {
      services.forEach(service => {
        const serviceDirective = this.findService(service.id);
        if (serviceDirective) {
          serviceDirective.handleStatus(service.status, service.version);
        }
      });
    });

  }
  ngOnInit(): void {
    const weatherURL = "https://publicdata-weather.firebaseio.com/";
    let city = new Firebase(weatherURL).child(this.city);

    this.currently = observableFirebaseObject(city.child('currently'));

    this.currently.subscribe(res => {
      this.current = res;
    });

    this.hourly = observableFirebaseArray(city.child('hourly/data').limitToLast(10));
  }
  constructor(private store: Store<AppStore>) {
    this.context = Observable.combineLatest(
        store.select('sessions'),
        store.select('selectedUser'),
        (sessions: Session[], selectedUser: User) => {
          return {
            sessions: sessions.filter(session => selectedUser.sessions.indexOf(session.id) > -1)
          };
        });

    this.context
      .subscribe(c => console.log('ContextService.context', c));
  }
Example #12
0
  public init(hour, minute) {
    this.normal = true;
    this.warning = false;
    this.alarm = false;
    this.currentTime = new Date();
    this.alarmTime = this.setAlarmTime(hour, minute);
    this.timer = Observable.timer(0,1000);

    let onTimerTick = this.timer.subscribe(x => {
      this.currentTime = new Date();
      this.checkAlarmTime();
    });
  }
    public ngAfterViewInit(): void {
        this.chart = new Chart(this.chartCanvasElement.nativeElement, {
            type: 'line',
            data: {
                labels: [],
                datasets: []
            },
            options: {
                scales: {
                    xAxes: [{
                        gridLines: {
                            color: "#333333",
                        }
                    }],
                    yAxes: [{
                        gridLines: {
                            color: "#333333",
                        }
                    }]
                }
            }
        });

        this.capacityHistory.subscribe(
            dataStream => {

                if (!dataStream) {
                    return;
                }
                
                dataStream.stream.subscribe(
                    next => {
                        this.addData(dataStream.name, next);
                    },
                    error => {
                        // this.removeData(dataStream.name);
                    },
                    () => {
                        this.removeData(dataStream.name);
                    }
                );
            },
            error => {
                console.log("error: " + error);
            },
            () => {
                console.log("complete");
            }
        );
    }
Example #14
0
  ngOnInit() {
    this.setup.subscribe(
      gamedata => {
        // This ChangeDetectorRef stuff needs to be here so the
        // controls on screen will be updated when data changes.
        this.ref.markForCheck();
        setInterval(() => {
          this.ref.markForCheck();
        }, 100);

        this.setupData = gamedata;
      }
    );
  }
  ngDoCheck() {
    if(!this.subscribed && isPresent(this.stream$)) {
      this.stream$.subscribe((e) => {
        this.materialized = false;
      });
      this.subscribed = true;
      console.log('mater subscribed!');
    }

    if (!this.materialized && $('.dropdown-button').length > 0) {
      $('.dropdown-button').dropdown({});
      this.materialized = true;
      console.log('materialized!');
    }
  }
    ngOnInit() {
        //this.mealProviderService.ngOnInit();
        this.mealProviders = this.mealProviderService.getDailyMealsByMealProviders();
        this.mealProviders.subscribe((array) => {
            for (var i = 0; i < array.length; i++) {

                var provider = array[i];
                if (i <= this.boxes.length) {
                    //TODO refactor, not too elegant -> map
                    this.boxes[i].mealProvider = provider;

                } else {
                    console.error('You have reached the maximal number of boxes! We can show in this version of the application only ' + this.boxes.length + ' boxes');
                }
            }
        });
    }
Example #17
0
    /**
     * Creates a new Reactive Command.
     * @param canRun An observable that determines whether the given task is allowed to run at a given moment.
     * @param task A function that returns an observable that represents the asynchronous operation.
     * @param scheduler The scheduler that all of the results should be observed on.
     */
    constructor(private task: (args: TArgs) => Observable<TResult>, private canRun: Observable<boolean>, private scheduler: Scheduler) {
        if (!task) {
            throw new Error("The task parameter must be supplied");
        }
        if (!canRun) {
            throw new Error("The canRun parameter must be supplied");
        }
        if (!scheduler) {
            throw new Error("The scheduler parameter must be supplied");
        }
        this._executionInfo = new Subject<ExecutionInfo<TResult>>();
        this._synchronizedExcecutionInfo = this._executionInfo;
        this._exceptions = new Subject<any>();

        // Implementation mostly taken from:
        // https://github.com/reactiveui/ReactiveUI/blob/rxui7-master/ReactiveUI/ReactiveCommand.cs#L628
        
        this._isExecuting = this._synchronizedExcecutionInfo
            .observeOn(scheduler)
            .map(info => info.demarcation === ExecutionDemarcation.Begin)
            .startWith(false)
            .distinctUntilChanged()
            .publishReplay(1)
            .refCount();
        this._canExecute = this.canRun
            .catch(ex => {
                this._exceptions.next(ex);
                return Observable.of(false);
            })
            .startWith(false)
            .combineLatest(this._isExecuting, (canRun, isExecuting) => {
                return canRun && !isExecuting;
            })
            .distinctUntilChanged()
            .publishReplay(1)
            .refCount();
        this._results = this._synchronizedExcecutionInfo
            .observeOn(scheduler)
            .filter(info => info.demarcation === ExecutionDemarcation.EndWithResult)
            .map(info => info.result);

        // Make sure that can execute is triggered to be a hot observable.
        this._canExecuteSubscription = this._canExecute.subscribe();
    }
Example #18
0
  ngOnInit() {
    this.game.subscribe(
      gamedata => {
        // This ChangeDetectorRef stuff needs to be here so the
        // controls on screen will be updated when data changes.
        this.ref.markForCheck();
        setInterval(() => {
          this.ref.markForCheck();
        }, 100);

        if(gamedata.playerOne && gamedata.playerTwo) {
          this.playerOne = gamedata.playerOne;
          this.playerTwo = gamedata.playerTwo;
          this.targetscore = gamedata.targetscore;
          this.possibleRun = gamedata.possibleRun;
        }
      }
    );
  }
Example #19
0
  ngOnInit() {
    this.isMapFullscreen$ = this._store
      .select(fromRoot.getMapSettings)
      .map(mapSetting => mapSetting.isFullscreen)
      .distinctUntilChanged();

    this.segments$ = this._store.select(fromRoot.getSegments);

    this.selectedSegment$ = this._store.select(fromRoot.getSelectedSegment);

    this.region$ = this._store.select(fromRoot.getRegion(this.regionId));

    this.section$ = this._store
      .select(fromRoot.getSelectedSection)
      .distinctUntilChanged();

    this.fetching$ = this._store.select(fromRoot.getSectionFetching);

    this._scrollToTopSubscription = this.section$.subscribe(() => {
      this.content.scrollToTop();
    });
  }
  ngOnInit(): void {
    this.messages = this.threadsService.currentThreadMessages;

    this.draftMessage = new Message();

    this.threadsService.currentThread.subscribe(
      (thread: Thread) => {
        this.currentThread = thread;
      });

    this.userService.currentUser
      .subscribe(
        (user: User) => {
          this.currentUser = user;
        });

    this.messages
      .subscribe(
        (messages: Array<Message>) => {
          setTimeout(() => {
            this.scrollToBottom();
          });
        });
  }
 private subscribeToSaveResponse(result: Observable<Codebadge>) {
     result.subscribe((res: Codebadge) =>
         this.onSaveSuccess(res), (res: Response) => this.onSaveError(res));
 }
 private subscribeToSaveResponse(result: Observable<Post>) {
     result.subscribe((res: Post) =>
         this.onSaveSuccess(res), (res: Response) => this.onSaveError(res));
 }
 onError(callback: (err: Message[]) => void) {
   this.messageObservable.subscribe(callback);
 }
 private subscribeToSaveResponse(result: Observable<Localidades>) {
     result.subscribe((res: Localidades) =>
         this.onSaveSuccess(res), (res: Response) => this.onSaveError());
 }
 .subscribe((action => {
   this.store.dispatch({type: EDIT_OPERATION, payload: operation});
   this.operations.subscribe((o) => {
     this.store.dispatch({type: INIT_COUNTER, payload: o});
   });
 }));
 private subscribeToSaveResponse(result: Observable<InternacoesDetalhes>) {
     result.subscribe((res: InternacoesDetalhes) =>
         this.onSaveSuccess(res), (res: Response) => this.onSaveError());
 }
 private subscribeToSaveResponse(result: Observable<DepartmentHotpersonel>) {
     result.subscribe((res: DepartmentHotpersonel) =>
         this.onSaveSuccess(res), (res: Response) => this.onSaveError(res));
 }
Example #28
0
// #docregion Observable
import {Observable, Subscriber} from 'rxjs/Rx';
var obs = new Observable<number>((obs: Subscriber<number>) => {
  var i = 0;
  setInterval(_ => { obs.next(++i); }, 1000);
});
obs.subscribe(i => console.log(`${i} seconds elapsed`));
// #enddocregion
 private subscribeToSaveResponse(result: Observable<Domain>, isCreated: boolean) {
     result.subscribe((res: Domain) =>
         this.onSaveSuccess(res, isCreated), (res: Response) => this.onSaveError(res));
 }
Example #30
0
 private subscribeToSaveResponse(result: Observable<Marcas>) {
     result.subscribe((res: Marcas) =>
         this.onSaveSuccess(res), (res: Response) => this.onSaveError());
 }