Http get Request always must fired twice to work? Help pls

It is difficult to say without knowing more about how the rest of your code is structured, but in general,

this.http.post('url', credentials).subscribe((rsp) => {
  // you can call rsp.text() or more typically rsp.json() here
  // but most importantly inside here is the only place you
  // can rely on having the response
});

If you are attempting to separate the backend callback from the client, which is a very typical situation, then it is best to return an Observable from your backend communication service. Often this is done with a map transform, like so:

authenticate(email: string, pwd: string): Observable<AuthToken> {
  return this.http.post('url', {email: email, pwd: pwd}).map((rsp) => {
    return rsp.json();
  });
};

Personally I use the heuristic of “instinctually have ‘return’ be the first thing you type in a function like this” (that is returning a future). There are some rare occasions where that’s not the case, but in the vast majority of cases it saves you from silly bugs. In particular, this very common idiom (which I have also been very harshly critical of here and drawn ire from mods for doing so).

So in this case, you would subscribe to the return value from authenticate, and inside that subscribe block would be the only place where you can rely on the value being accurate.

In a common situation, you would be assigning that value to a property in a component controller, which would be referenced by a template, often in an ngFor loop. It is imperative that you either protect in the template against that variable having not been initialized yet (which I think is a suboptimal but defensible alternative) or to initialize the property to a functioning dummy (my preferred solution), such as an empty array or blank string. That way your app will function smoothly without needing to resort to brittle timeouts.

1 Like