1

I have following service in Angular 7:

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

@Injectable()
export class UserService {

  private currentUserSubject: BehaviorSubject<any>;

  constructor(
    private http: HttpClient
  ) {
    this.currentUserSubject = new BehaviorSubject(null);
  }

  public get currentUserValue(): any {
    return this.currentUserSubject.value;
  }

  login(entity: any, inputUsername: any, inputPassword: any): any {

    const httpOptions = {
      headers: new HttpHeaders({
        username: inputUsername,
        password: inputPassword
      })
    };

    return this.http.get(entity.url, httpOptions)
    .pipe(map((user: Response) => {
      console.log(user);
      console.log(user.status);

      if (user) {
          this.currentUserSubject.next(user);
      }
      return user;
  }));
  }
}

I want to get the response status (200, 401, etc.). If I try to subscribe such as .pipe(map(.....)).subscribe(...), I get error that subscribe is not a function.

Also, I get only the 200 status responses in pipe(map()). I do not get responses with other status codes here.

I want to update the BehaviorSubject based on the received status.

How can I get all the responses and their status in the service?

I have gone though Angular 6 Get response headers with httpclient issue, but that does not apply here.

I added observe: 'response' to http headers, but it did not make any difference.

const httpOptions = {
      headers: new HttpHeaders({
        username: inputUsername,
        password: inputPassword,
        observe: 'response',
      }),
    };
3
  • So you are using {observe: 'response'} and it didnt work ? Commented May 21, 2019 at 3:52
  • @TonyNgo How can I add {observe: 'response'} in my httpOptions? Commented May 21, 2019 at 3:56
  • @TonyNgo {observe: 'response'} did not work for me Commented May 21, 2019 at 5:57

3 Answers 3

1

This is how I did it :

this.http.get(this.url, { observe: 'response' })
  .subscribe(response => console.log(response.status));

Using Angular HttpClient and subscribing to the observable returned from http.get.

Sign up to request clarification or add additional context in comments.

2 Comments

But I also need to pass my headers in the request. How can I add {observe: 'response'} in my httpOptions?
import { HttpHeaders } from '@angular/common/http'; So you will build up the headers as follows: let headers = new HttpHeaders(); headers = headers.set('Authorization', 'Basic xzeydyt==');
0

in Angular 7, the best way to add header to the request is, using the interceptor. in the interceptors, you can add header to the request and as a result, you can access to the protected API. here is the interceptor sample which adds header to the request :

       intercept(request: HttpRequest<any>, next: HttpHandler): 
            Observable<HttpEvent<any>> {
            let currentUser = this.authservice.currentUser;
         if (currentUser && currentUser.token) {
           request = request.clone({
           setHeaders: {
           Authorization: `Bearer ${currentUser.token}`
           }
          });
         }

         return next.handle(request)

Comments

0

Tell HttpClient that you want the full response with the observe option:

const httpOptions:any = {
  headers: new HttpHeaders({
    username: inputUsername,
    password: inputPassword
  }),
  observe: 'response',
};
return this.http.get<any>(entity.url, httpOptions) //I put the type of the response data as `any` you can put the type of user
 .pipe(map((user: HttpResponse<any>) => {//same type as above statement
   console.log(user);
   console.log(user.status);

   if (user) {
      this.currentUserSubject.next(user);
   }
   return user;
 }));

Now HttpClient.get() returns an Observable of typed HttpResponse not just the JSON data.

4 Comments

I get error: Types of property 'observe' are incompatible. Type 'string' is not assignable to type '"body"'.
can you put httpOptions type to any. I had edited it in the answer
adding any gives me error: Type 'Response' is missing the following properties from type 'ArrayBuffer': byteLength, slice, [Symbol.toStringTag]
Can you check the edited code? I added the pipe you put in the question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.