无法通过 HTTP GET 请求存储数据 - 潜在的可观察/异步订单问题

Unable to store data through HTTP GET request - potentially Observable / Asynchronous order issue

我正在从 onSubmit() 调用服务。然后服务调用 REST API 获取数据。但是顺序不是我所期望的。 我想我这里有 2 个问题:

  1. 日志 @@@ CUSTOMER BEFORE RETURN 似乎不包含检索到的数据,尽管在方法开始时初始化了变量。所以在这个日志行,它仍然是 undefined。但是在 @@@ UNPACKED DATA 处数据是可见的。
  2. 即使 customerloadCustomer 的 return 处未定义,看起来行 @@@ CUSTOMER IN onSubmit 是在检索数据之前而不是之后执行的,这会有问题,因为我之后需要使用这些数据!
  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"}

从我收集到的信息来看,这似乎与 Observable/某种形式的异步操作有关,但是我无法弄清楚我哪里出错了。

您在 http 调用 returns 之前 returning 一个对象,您需要 return 一个可观察对象,然后在组件中订阅它:

onSubmit(customerData) {
  this.customerService.loadCustomer(customerData)
    .subscribe((res) => {
        console.log("@@@ CUSTOMER IN onSubmit", res)
        // use res Object to process orders...
    })
}

并在您的 loadCustomer 函数中:

loadCustomer(customerId: number) {
  const httpOptions = {
      headers: new HttpHeaders({
          'Content-Type': 'application/json'
      })
  };

  return this.http.get<any[]>('https://REGION.amazonaws.com/dev/customer', httpOptions)
    .pipe(map((result) => {
        const myStr = JSON.stringify(data);
        const myObj = JSON.parse(myStr);
        let customer; 

        console.log("@@@ UNPACKED DATA", myObj['data']['Items'][customerId-1])
        if (typeof myObj['data']['Items'][customerId] != "undefined") {
            customer = myObj['data']['Items'][customerId-1];
        }
        
        return customer;
    }));
}