简体   繁体   中英

Angular6 Post Method Wrong Output

I am using Post Method for my Login in Angular 6, I was always getting Failed to Login when I even gave correct Login Credentials and when i debug my code i found its sending headers as null even if I included my headers.

This is my code when I debug and its showing response is not defined:

case 'json':default:return res$.pipe(map(function (res) { return res.body; }));

My Ts File

import { Injectable } from '@angular/core';
import { RequestOptions, Headers, Response } from '@angular/http';
import { map } from 'rxjs/operators';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  baseUrl = "http://localhost:3000/api/auth";
  userToken: any;
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  };

  constructor(private http: HttpClient) {}

  login(loginData: any) {
    return this.http.post(this.baseUrl, loginData, this.httpOptions)
    .pipe(
      map((response: Response) => {
        const user = response.json();
        if (user) {
          localStorage.setItem('token', user.token);
          this.userToken = user.token;
        }
      })
    )
  }

}

Thanks in Advance

HttpClient does response.json() for you, so it only returns the body of the response. Also you probably do not need to set any header options, it should be application/json by default.

login(loginData: any) {
  return this.http.post(this.baseUrl, loginData);

}

Should be enough. This will return an observable you can subscribe to.

So in your component you can do:

this.authService.login(data).subscribe((user) => {
if (user) {
 localStorage.setItem('token', user.token);
}
else {
// What to do when there is no token
// Ideally you would want to throw an error on the server along the     
// lines of code 403. 
} 
});

If you do return a status code like 403 you need to catch the error though, like this: https://www.learnrxjs.io/operators/error_handling/catch.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM