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

Fetch http data before send http request in Angular 2 with RxJS

我有注册表,我需要发送带有 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 令牌时等待?

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

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

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

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

或者更好地使用可观察对象的组合运算符:

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