首页 > 解决方案 > 无法通过 HTTP GET 请求存储数据 - 可能是可观察/异步订单问题

问题描述

我正在从 onSubmit() 调用服务。然后该服务调用 REST API 获取数据。然而,订购不是我所期望的。我想我在这里有两个问题:

  1. 尽管在方法开始时初始化了变量,但日志@@@ CUSTOMER BEFORE RETURN似乎不包含检索到的数据。所以在这个日志行,它仍然是undefined. 然而在@@@ UNPACKED DATA数据是可见的。
  2. 即使customer在返回时不是未定义的loadCustomer,看起来该行@@@ 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/某种形式的异步操作有关,但是我无法理解我在哪里出错了。

标签: javascriptangularobservable

解决方案


您在 http 调用返回之前返回一个对象,您需要返回一个 observable 然后在组件中订阅它:

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;
    }));
}

推荐阅读