0

I start learning angular with typescript for a while and now I face a situation that I couldn't figure out how I should solve. I have two methods in a class method A and method B. Both of them send a request to the database to receive some information. the problem is when I call method B inside method A the value that I receive from method B is not updated, it shows me the value for the previous call, how I can overcome this situation so when I call method B in method A it shows me the fresh result.

@Injectable()
export class foo{
   id: number;

   async method_A(){
     this.method_B();
     console.log(this.id);   // in here after I call method_B it should show me the correct value 
                             // but it will show me the value for previous call to database.
     await this.http.get<any>("url").subscribe(data => {})
   }

   method_B(){
      this.http.get<any>("url").subscribe(data => {
         this.id = data.id;
      })
   }
}

things that I tried so far:

First, I used await when I call the method_B but it doesn't work.

Second, I tried to use a BehaviorSubject and assign the id in it and return it as an asObservable and subscribe to it inside method_A, but still the result is not what I want. in this case, the method will call twice and the first time the value is the old value, and the second time it will return the updated value which is not useful for me because in another file I always receive the value from the first time call.

Ali Ansari
  • 152
  • 1
  • 1
  • 15
  • Does this answer your question? [How do I return the response from an Observable/http/async call in angular?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular) – R. Richards Nov 23 '20 at 20:25

1 Answers1

0

If you want to continue in method_A after method_B got the result, then you should return a promise from method_B to await in method_A. You can convert an observable to a promise with toPromise which will help you do that:

method_B() {
    return this.http.get<any>("url").toPromise()
}

Then you can await that result in method_A and assign this.id there:

async method_A(){
    const { id } = await this.method_B();
    this.id = id;
    console.log(this.id); // This should be up-to-date now
}
JJWesterkamp
  • 7,559
  • 1
  • 22
  • 28
  • I tried the exact same thing but it shows me **undefined**, also I am wondering if I need to subscribe in method_B to do other things besides assigning value to **id** how I am suppose to do that? because we can't use "toPromise()" after "subscribe()". – Ali Ansari Nov 23 '20 at 21:37