在使用RxJS在Angular 2中发送http请求之前获取http数据

时间:2016-03-27 13:22:44

标签: angular rxjs angular2-services

我有注册表格,我需要发送带有csrf令牌的表格,在填写表格之前我应该​​发送。没有工作代码,但它有我想要的想法。

var model = {
            username : this.form.value.username,
            email : this.form.value.email,
            password_second : this.form.value.password_second,
            password : this.form.value.password,
            csrf : ''
        };
        this._csrfService.getToken().subscribe(
            csrf => model.csrf,
            error => console.log(error)
        );
        this._signUpService.sendForm(model)
            .subscribe(
                hero  => console.log(hero),
                error =>  console.log(error));

SignUp和Csrf服务显而易见:

getToken()
    {
        console.log(this.http.get(this._sighUpUrl));
        return this.http.get(this._sighUpUrl)
            .map(res =>  res.json().data.csrf)
            .catch(this.handleError)
    }

sendForm(name:Object)
    {
        let body = JSON.stringify(name);
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        console.log(this.http.post(this._sighUpUrl, body, options));
        return this.http.post(this._sighUpUrl, body, options)
            .map(res =>  res.json().data)
            .catch(this.handleError)
    }

如何等待我没有获得csrf令牌?

2 个答案:

答案 0 :(得分:2)

您可以从第一个回调中发送第二个请求:

var model = {
    username : this.form.value.username,
    email : this.form.value.email,
    password_second : this.form.value.password_second,
    password : this.form.value.password,
    csrf : ''
};
this._csrfService.getToken().subscribe(
    csrf => {
      model.csrf = csrf;
      this._signUpService
        .sendForm(model)
        .subscribe(
          hero  => console.log(hero),
          error =>  console.log(error)
        );
    },
    error => console.log(error)
);

或者更好地使用observables的合成运算符:

var model = {
    username : this.form.value.username,
    email : this.form.value.email,
    password_second : this.form.value.password_second,
    password : this.form.value.password
};
this._csrfService
  .getToken()
  .map(csrf => Object.assign({csrf:csrf}, model))
  .flatMap(model => this._signUpService.sendForm(model))
  .subscribe(
    hero  => console.log(hero),
    error =>  console.log(error)
  );

答案 1 :(得分:1)

您可以使用observables的flatMap运算符,如下所述:

getToken().flatMap(token => {
  return sendForm(...);
}).subscribe(...);