0

Hi I am trying to do something with the result of a http request but my callback is never being executed and I can't wrap my head around why..

I've followed the example from here on this part..

This is my code:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import * as moment from "moment";
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/shareReplay';

@Injectable()
export class AuthdataService {
constructor(private http: HttpClient) {}

login(email: string, password: string) {

  return this.http
    .post("http://localhost:3000/user/login", {
      email,
      password
    })
    .do(res => this.setSession)
    .shareReplay();
  }

  private setSession(authResult) {
  console.log("Why am I not being hit???")
  const expiresAt = moment().add(authResult.expiresIn,'second');

  localStorage.setItem('id_token', authResult.idToken);
  localStorage.setItem("expires_at", JSON.stringify(expiresAt.valueOf()) );
  }  
}

Updated solution:

login(email: string, password: string) {

return this.http
  .post("http://localhost:3000/user/login", {
    email,
    password
  })
  .do(res => this.setSession(res))
  .shareReplay();   
  }

1 Answer 1

2

You are expecting the Observable sequence you're creating to be "hot", but instead it is "cold". The difference is described elsewhere on the internet in terms better than I can manage.

In other words, the .post doesn't actually do anything until it is subscribed to. Reference.

Invoking shareReplay doesn't subscribe to the Observable, but only ensures that up to one subscription to the underlying Observable will ever be created at once.

So the missing link is probably a call to .subscribe on the Observable you have created.

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

4 Comments

Hi thank you for your answer - I'm surprised the Angular University example did not work.
So it works if I add ".subscribe(this.setSession);" after shareReplay() but I need to do statement to call shareReplay but what should be in the argument of .do() then?
Since this is a service I can't subcsribe in my components if I add a subscribe here.. I ended up finding a solution which essentially just was a silly mistake ..
@J.Kirk. I see your updated solution. Sorry I didn't notice that!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.