import { Observable } from 'rxjs/Observable' ; import { Injectable } from '@angular/core' ; import { Store } from '@ngrx/store' ; import _get from 'lodash/get' ; import { AppState , ITwitterUser } from '../../reducers' ; import { TwitterProvider } from './../twitter/twitter' ; import { addTwitterUser } from '../../actions' ; @ Injectable ( ) export class UsersProvider { constructor ( public store , private twitterProvider ) { console . log ( 'Hello UsersProvider Provider' ) ; } getCurrentUser$ ( ) { return Observable . combineLatest ( this . store . select ( state => state . auth . screen_name ) , this . store . select ( state => state . users ) , ( screen_name , users ) => screen_name && _get ( users , `[${ screen_name }]` ) ) ; } getCurrentUser ( ) { let user ; this . getCurrentUser$ ( ) . first ( ) . subscribe ( ( u ) => user = u ) ; return user ; } doesUserExist ( handle ) { let doesUserExist ; this . getUserById$ ( handle ) . first ( ) . subscribe ( ( u ) => doesUserExist = typeof u !== 'undefined' ) ; return doesUserExist ; } fetchUser$ ( handle ) { return this . twitterProvider . getUser$ ( handle ) . debounceTime ( 500 ) . map ( user => this . store . dispatch ( addTwitterUser ( user ) ) ) . catch ( error => { return Observable . of ( null ) ; } ) ; } getUserById$ ( handle = '' ) { return this . store . select ( state => state . users [ handle . toLowerCase ( ) ] ) ; } }