Saturn
Saturn

Reputation: 430

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

I have registration form and I need to send this form with csrf token, which I should get before filled form will be send. There is not working code, but it have idea what I want.

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 and Csrf Services are obvious:

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

How to wait while I don't get csrf token?

Upvotes: 1

Views: 1297

Answers (2)

Tamas Hegedus
Tamas Hegedus

Reputation: 29946

You could just send the second request from the callback of the first:

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

Or much better to use the composition operators of 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)
  );

Upvotes: 2

Thierry Templier
Thierry Templier

Reputation: 202306

You could use the flatMap operator of observables, as described below:

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

Upvotes: 1

Related Questions