Rxjs - 重构

直接重构后代码对比吧.感觉有进步

import {HTTP_PROVIDERS, Http, Response} from 'angular2/http';
import {Injectable} from 'angular2/core';
import {ProjectInfo} from './../model/project.model';
import {baseURL, HeaderWithToken} from './config';
import { DialogServices } from './dialog.services';
import Rx from 'rxjs/Rx';



let cacheProject: Array<ProjectInfo> = [];

export let getAllProjects: Rx.BehaviorSubject<ProjectInfo[]> = new Rx.BehaviorSubject(cacheProject);

@Injectable()
export class ProjectService {

_create: Rx.Observable<Response> = new Rx.Observable();
newProject: Rx.Subject<ProjectInfo> = new Rx.Subject();
_get: Rx.Observable<any> = new Rx.Observable();
res$: Rx.Observable<any> = new Rx.Subject().asObservable();

constructor(public _http: Http, public option: HeaderWithToken) {

//any new value into the newProject will deliver to post and save as create stream
//to check the status code in the create stream to close dialog
this._create = this.newProject
.flatMap(
project => {
return this._http
.post(
baseURL + "/project",
JSON.stringify(project),
this.option.Option
);
});

this.res$ = this._create
.filter(res => res.status == 200)
.flatMap(x => {
DialogServices.getRef()
.then(x => {
x.dispose();
})
return this._get;
})

//For get all project from DB, will return an array of projectInfo
this._get = this._http
.get(baseURL + "/project", this.option.Option)
.map(res => res.json());

this.res$.subscribe(x => {
cacheProject = x;
console.log("cache", x, cacheProject);
getAllProjects.next(cacheProject);
})
}
addProject(project: ProjectInfo) {
this.newProject.next(project);
}
}

有点函数式的影子了.鼓励自己一下.准备入门