2

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.

quma
  • 5,233
  • 26
  • 80
  • 146

3 Answers3

1

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;
}
The Segfault
  • 939
  • 1
  • 10
  • 23
1

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

David
  • 33,444
  • 11
  • 80
  • 118
0

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

...map( res => this.loginResponse = res.json() )
Mixalloff
  • 827
  • 4
  • 10
  • res.json() is deprecated with the latest HttpClient and no longer available when using angular 5. https://stackoverflow.com/questions/46630893/angular-res-json-is-not-a-function?noredirect=1&lq=1 – alsami Feb 20 '18 at 15:38
  • Yes, json received by default in angular 5 – Mixalloff Feb 20 '18 at 15:47