quma
quma

Reputation: 5743

Angular 5 / Typescript/RxJS - get data from Observable

I have this typescript method in order to login user:

onSubmit() {
    if (this.form.valid) {
      this.authService.login(this.form.value).map(res => this.loginResponse = res.json).subscribe(
        success => {
          console.log('Response: ' + this.loginResponse);
        },
        error => {
          this.loginFailed = true;
          setTimeout(()=>{   
            this.loginFailed  = false;
          }, 3000);
          console.error('ERROR login.component: ' + error);
        }
      );     
    }
    this.formSubmitAttempt = true;            
  }

and actually I don't know how to get the response data inhere .map(res => this.loginResponse = res)

The output of console.log is:

Response: function () {
    if (typeof this._body === 'string') {
        return JSON.parse(/** @type {?} */ (this._body));
    }
    if (this._body instanceof ArrayBuffer) {
        return JSON.parse(this.text());
    }
    return this._body;
} 

Does anyone have any hint how I get the response object with observables.

Upvotes: 2

Views: 2736

Answers (3)

David
David

Reputation: 34465

Try that

this.authService.login(this.form.value).map(res => res.json()).subscribe(
    resp => {
     this.loginResponse = resp;
      console.log('Response: ' + this.loginResponse);
    },
    error=> //...

If using angular 5, you should use HttpClient instead of the deprecated Http class. That way, you won't even need to call

.map (res=>res.json())

as httpClient automatically converts the response to json format by default

Upvotes: 1

The Segfault
The Segfault

Reputation: 1040

If you are on Angular5 with HttpClient instead of Http then I think you might be able to just remove .map and do this:

onSubmit() {
    if (this.form.valid) {
        this.authService.login(this.form.value)
            .subscribe(
                success => {
                    this.loginResponse = success;
                    console.log('Response: ' + success);
                },
                error => {
                    this.loginFailed = true;
                    setTimeout(() => {
                        this.loginFailed = false;
                    }, 3000);
                    console.error('ERROR login.component: ' + error);
                }
            );
    }
    this.formSubmitAttempt = true;
}

Upvotes: 1

Mixalloff
Mixalloff

Reputation: 837

response.json is a function. You need to call them

...map( res => this.loginResponse = res.json() )

Upvotes: 0

Related Questions