1

I am trying to create a simple post in a service class using Angular/Typescript My IDE does not give me any error, but when I call the function, I am getting undefined. I am not sure where the problem is based. I did some research, and it seems like the problem might be with the HttpClient I am importing, but I can not find anything relevant.

Front-end Function:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders} from '@angular/common/http';
import { Response } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class ServiceClassAuth {
  auth: any;
  user: any;
  constructor(private http: HttpClient) {}

  signinUser(user) {}

  login(user) {
    let headers = new HttpHeaders();
    headers.append('Content-Type', 'application/json');
    const loginUrl = 'http://localhost:3000/login';
    return this.http.post(loginUrl, user, {
      headers: headers
    }).map((res: Response) => res.json());
  }
}

A component which calls the Service:

import { Component, OnInit } from '@angular/core';
import {
  MatDialog,
  MatDialogRef,
  MAT_DIALOG_DATA
} from '@angular/material';
import { Inject } from '@angular/core';

import { ServiceClassAuth } from '../service/service-class-auth';


@Component({
  selector: 'app-signin',
  templateUrl: './signin.component.html',
  styleUrls: ['./signin.component.css'],
  providers: [ServiceClassAuth]
})
export class SigninComponent implements OnInit {
  username: String;
  password: String;

  ngOnInit() {}

  constructor(
    public dialogRef: MatDialogRef < SigninComponent > ,
    @Inject(MAT_DIALOG_DATA) public data: any,
    private authService: ServiceClassAuth) {}

  onNoClick(): void {
    this.dialogRef.close();
  }

  loginSubmit(postValues): void {
    const user = {
      'usr': postValues.value.usrname,
      'psw': postValues.value.psw
    }

    const res = this.authService.login(user).subscribe(res => {
      if (res.success) {

      } else {
        //DO ALERT
      }
    });
  }
}
Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
NashPL
  • 461
  • 1
  • 4
  • 19
  • I think you need to use .subscribe instead of .map, as detailed in the Angular documentation https://angular.io/guide/http#getting-json-data. Let me know if that helps – NocNit May 23 '18 at 23:42

1 Answers1

3

With HttpClient (Angular 4.3+), you do not have to use res.json() , the response object is JSON by default, Just use response directly.

return this.http.post(loginUrl, user, {
      headers: headers
    }).map((res: Response) => res);
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396