I'm calling a Service from an onSubmit(). The service then calls a REST API for data. However the ordering is not what I'd expect. I think I have 2 issues here:
- The log @@@ CUSTOMER BEFORE RETURNdoesn't seem to contain the retrieved data despite initialising the variable at the start of the method. So at this log line, it's stillundefined. However at@@@ UNPACKED DATAthe data is visible.
- Even if customerwas not undefined at the return ofloadCustomer, it looks like the line@@@ CUSTOMER IN onSubmitis executed before data is retrieved and not after, which will be a problem since I need to use the data afterwards!
  onSubmit(customerData) {
    let customer = this.customerService.loadCustomer(customerData)
    console.log("@@@ CUSTOMER IN onSubmit", customer)
    // use customer Object to process orders...
  }
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable()
export class CustomerService {
    constructor(private http: HttpClient) { }
    loadCustomer(customerId: number) {
        console.log("@@@ Customer ID to get: ", customerId)
        var myStr: string;
        var myObj: any;
        var customer: Object
        const httpOptions = {
            headers: new HttpHeaders({
                'Content-Type': 'application/json'
            })
        };
        this.http.get<any[]>('https://REGION.amazonaws.com/dev/customer', httpOptions).subscribe(
            data => {
                myStr = JSON.stringify(data);
                myObj = JSON.parse(myStr);
                console.log("@@@ UNPACKED DATA", myObj['data']['Items'][customerId-1])
                if (typeof myObj['data']['Items'][customerId] != "undefined")
                    customer = myObj['data']['Items'][customerId-1]
            },
            error => console.log('Failed to get customer.')
        );
        console.log("@@@ CUSTOMER BEFORE RETURN: ", customer)
        return customer;
    }
OUTPUT IN CONSOLE:
customer.service.ts:21 @@@ Customer ID to get:  2
customer.service.ts:51 @@@ CUSTOMER BEFORE RETURN:  undefined
cart.component.ts:64 @@@ CUSTOMER IN onSubmit undefined
customer.service.ts:38 @@@ UNPACKED DATA {customer_id: 2, address: "32 Big avenue", row_id: "a97de132-89ac-4f6e-89cd-2005319d5fce", name: "Dave Lawinski", tel_number: "777888999"}
From what I've gathered this looks like something to do with Observable / some form of asynchronous operation, however I've not been able to make sense of where I'm going wrong here.
 
    