Search code examples
angularasynchronousobservable

how to execute callback sequentially in Angular


How to enforce Angular to wait until fetching data is completeley finished before resuming the execution in ngOnInit:

fetchdata() {
    console.log('2')
   
   this.http.get("http://jsonplaceholder.typicode.com/users").subscribe(
     (data) => {
         console.log('3')
         return data
    })
}

ngOnInit() {
    console.log('1')
    this.httpdata = this.fetchdata()
    console.log('4')
}

in the example above, the order of console.log is 1, 2, 4, 3

I know that get function of httpclient is asynchron, but how can I make my function fetchdata asynchron too?

just declaring the function as async keeps the console.log in same order, and throws execution time error too:

async fetchdata() {
    console.log('2')
    this.http.get("http://jsonplaceholder.typicode.com/users").subscribe(
     (data) => {
        console.log('3')
        return data
    })
}

How can I declare my function fetchdata as observable?


Solution

  • One way to achieve this is by subscribing to the method.

    ngOnInit() {
       console.log('1')
       this.fetchdata().subscribe({
          next: (data: string) => { 
    
            this.httpdata = data;
            console.log('4')},
    
          error: (error) => { }
       });
    }
    

    Note: this is for an API call scenario where you are expecting an ok from the server or an error.