0

I'm having problem getting a simple http call to work.

I came from angularjs and AFAIK .then = .subscribe

So Here's my problem, Can I not use the .subscribe in my auth-service and instead use it in my login.component.ts and I want to get the Http Status also.

auth.service

const httpOptions = {
   headers: new HttpHeaders({
       'Content-Type': 'application/json'
    })
}

export class AuthService {
 constructor(private http: HttpClient) { }
 mainUrl = 'http://localhost:4000/api/v1';
 signIn(user: User) { // this is working fine, BUT I want to use .subscribe in login component
    const url = `${this.mainUrl}/sign_in`;
    return this.http.post<any>(url, user, httpOptions)
    .subscribe(
    (data) => {
      console.log(data); // I want to get the 200 status not only the jwt token
      return data;
    },
    (error) => console.log(error)
  )
 }
}

login.component.ts

this.authService.signIn(userData); // how to use .subscribe here ? 

UPDATE:

Here's what my angularjs code look like.

auth.service

function signIn(data) {
        return $http.post(url + '/api/v1/sign_in_2', data)
            .then(success)
            .catch(fail);

        function success(response) {
            setToken(response.data.jwt);
            return response;
        }

        function fail(e) {
            return e;
        }
    }

login.ctrl

vm.doLogin = function (userData) {
  vm.spinner = true;
  elixirAuthServices.signIn(userData).then(function (data) {

    if (data.status === 200 || data.status === 201) {
      elixirAuthServices.getUser().then(function (data) {
        vm.user_id = data.data.id;
        redirect();
      });
    } else {
      vm.authenticateErr = true;
      vm.spinner = false;
      logger.info('Username or Password is incorrect');
    }

  });
};

3 Answers 3

5

You are close, but you should make the following modifications to your service.ts. Don't forget to import the required RxJS operators such as pipe, and map, if you are intending to use them.

import { catchError, map, tap } from 'rxjs/operators';

signIn(user: User) {
  const url = `${this.mainUrl}/sign_in`;
  return this.http.post<any>(url, user, httpOptions).pipe(
    // additional operations before returning observable
    //map(data => ....), 
    //catchError(this.handleError('signIn', []))
  );
 }

On your component.ts, you can return the observable by subscribing to it. The subscribe method handles the callback for next, error, and complete.

this.authService.signIn(userData).subscribe(success => {
   // next
   // .. handle successful response (status code 200)
}, error => {
   // handle errors
   console.log(error.status)
}, () => {
   // complete 
})

Edit: If you want to read the FULL response body, you can use the observe option

this.http.post<any>(url, user, { observe: 'response' }).pipe(
    //additional operations before returning observable
    //tap(response => console.log(response.status)
    //map(response => response.body), 
    //catchError(this.handleError('signIn', []))
  );
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks this is like how I did it in angularjs, but I still have the problem of only getting the jwt token how to get the http code status ?
Hey, just to check, are you referring to the getting the HTTP code status on success, or error?
I'm referring to the success
Hmm.. For success, wouldn't it always be code 200? Hmm.. Let me think.. If I am missing something here..
If you really want to access the response body (status code, status text, etc) even for your success response, you need to pass an additional optional parameter to your http.post() method. Let me update my answer!
|
1

RxJs Observable

    signIn(user){
        return this.httpClient.post<any>(url, user, option)
            .pipe(
            map(res => res),
            retry(1),
            catchError(err => throwError(err))
            )
    }

then you can subscribe response and catch error at LoginComponent

   this.authService.signIn(userData).subscribe(res => {
       // do something here
       }, err => {
       // catch err here 
       }
       )

Comments

1

subscribe() is not the same as then() method in Promise. You need to just return the result of http.post() which is Observable object and then subscribe the observable in the component.

And if you want to catch error, chain catch() method in the service.

auth.service.ts

signIn(user: User) { 
  const url = `${this.mainUrl}/sign_in`;
  return this.http.post<any>(url, user, httpOptions)
    .pipe(
      tap(val => console.log(val)), // do what you want with val
      catchError(error => console.log(error))
    )
}

login.component.ts

this.authService.signIn.subscribe(userData => {
  // do what did in login.ctrl
});

1 Comment

I tried this its throwing an error on catch saying 'catch' does not exist., second is I want to get the value of the request in my service

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.