Created
March 31, 2017 13:08
-
-
Save Deviad/b9d306d0dddb14244484473e00844c7e to your computer and use it in GitHub Desktop.
Read a JSON asynchronously and create an observable
out of it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Created by Davide Pugliese on 26/02/17. | |
*/ | |
import {Observable, Subscribable} from "rxjs/Observable"; | |
import "rxjs/add/observable/from"; | |
import "rxjs/add/observable/fromPromise"; | |
import "rxjs/add/observable/of"; | |
import "rxjs/add/operator/map"; | |
import "rxjs/add/observable/defer"; | |
import * as path from 'path'; | |
import {Observer, Subject} from "rxjs"; | |
// const request = require('request'); | |
const fs = require('fs'); | |
const Promise = require('promise'); | |
interface IUser { | |
id: String; | |
pw: String; | |
} | |
class User { | |
public id; | |
public pw; | |
} | |
class UserFactory { | |
build() { | |
//We create a promise in order to decouple this precise "user feed" from the rest of the code. | |
//In other words the code is ready for multiple "user feeds" as for example an API without having to refactor | |
//later on. | |
let readFile = Promise.denodeify(require('fs').readFile); | |
return readFile(path.join(__dirname, '..', '.env.json'), 'utf8') | |
.then( | |
(x) => { | |
let a = JSON.parse(x); | |
let user = new User(); | |
user.id = a.id; | |
user.pw = a.pw; | |
// console.log(JSON.stringify(user)); | |
return user; | |
} | |
); | |
} | |
} | |
let user = new UserFactory(); | |
let userObservable = Observable.from(user.build()); | |
userObservable.subscribe(x => console.log(JSON.stringify(x))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment