0

代码在这里:

@Injectable()
export class ProjectService {
  create$: Rx.Subject<Response> = new Rx.Subject();
  _create: Rx.Observable<Response> = this.create$.asObservable();
  newProject: Rx.Subject<ProjectInfo> = new Rx.Subject();
  get$: Rx.Subject<any> = new Rx.Subject();
  _get: Rx.Observable<any> = this.get$.asObservable();

  constructor(public _http: Http, public option: HeaderWithToken) {
    this._create = this.newProject.flatMap(project => {
      console.log("create",project);
      return this._http.post(baseURL + "/project",
               JSON.stringify(project), this.option.Option);
    });

    this._get = this._http
      .get(baseURL + "/project", this.option.Option)
      .do(x=>{
        console.log("to get",x);
      })
      .map(res => res.json());

    this._create
          .map(x=>x.json())
          .filter(res=>res.status==200)
          .subscribe(this.get$);

    this._get.subscribe(x => {
      console.log("get:", x);
    })
  }

  addProject(project: ProjectInfo) {
    this.newProject.next(project);
  }

  getProject() {
    return this._get;
  }
}

我希望流将作为 1 工作。当我调用 addProject => 发出值 => 触发发布请求 => 当发布响应 200 继续获取请求(_get 流)=> 我可以订阅 get$ 流其他地方来获取所有最新数据。

实际上:发布成功,但没有进入get请求,似乎代码有问题

    this._create
    .map(x=>x.json())
    .filter(res=>res.status==200)
    .subscribe(this.get$); 

请帮忙!

4

1 回答 1

0

我让它工作。

@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);
  }
}

于 2016-03-25T12:32:36.620 回答