0

can somebody help mewhy i got an error in my Angular code when i want to use HttpHeaders to read response status from backend? This is the clear error https://i.stack.imgur.com/tQu5t.jpg

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

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

  // Base api url
  public url = 'http://localhost:8080/';
  headerProperty: string;

  constructor(private http: HttpClient) { }

  createUser(data) {
    return this.http.post(this.url + 'todo', data);
  }

  createAddress(data) {
    return this.http.post(this.url + 'address', data);
  }

  loginstudent(data) {
    const postHttpOptions = {
      headers: new HttpHeaders({
      'Content-Type':  'application/json'
   }),
  observe: 'response' as 'body'
 };

  return this.http.post('http://localhost:8080/' + 'login', data, 
postHttpOptions)
  .pipe(map(response => {
         return response;
    }));

  }
}

I already edit the code and add as 'body' into my code but now i have a new problem with my component

saveStudentDetails(values) {
  const studentData = new FormData();

  studentData.append('id', values.id);
  studentData.append('password', values.password);
  this.crudService.loginstudent(studentData).subscribe(result => {
    if (result.headers.status === '202') {
      this.router.navigate(['address']);
      alert('"success"');
      return;
    }
  });
}

It says property 'headers' does not exist on type 'object'.

Dory
  • 95
  • 4
  • 19

1 Answers1

0

You're getting the error because result is of type {} which doesn't have any properties. You need to give it a type doing either of the following:

this.http.post<any>(...)

Or

(result: any)

But any shouldn't be used since it is poor TypeScript. Instead specify what your response looks like in a custom interface, for example:

export interface ICustomResponse {
  data: any;
  error: string;
}

And then use it like:

this.http.post<ICustomResponse>(...)

Or

(result: ICustomResponse)
Chrillewoodz
  • 27,055
  • 21
  • 92
  • 175
  • i already make the interface but in my login component saveStudentDetails() on the if else statement it says the headers does not exists in the interface – Dory Mar 11 '19 at 15:30