【问题标题】:Unable to store data through HTTP GET request - potentially Observable / Asynchronous order issue无法通过 HTTP GET 请求存储数据 - 可能是可观察/异步订单问题
【发布时间】:2020-12-22 14:32:59
【问题描述】:

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

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

【问题讨论】:

  • 感谢您 - 抱歉,它并没有完全解决问题。所以从那篇文章中我了解到subscribe 函数是“异步”的。所以我尝试从subscribe() 中返回customer,但它仍然在获取数据之前而不是之后调用@@@ CUSTOMER IN onSubmit 行,因此输出基本相同:(

标签: javascript angular observable


【解决方案1】:

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

【讨论】:

  • 谢谢。但是,在尝试使用 map 函数时,我收到了 Property 'map' does not exist on type 'Observable&lt;any[]&gt;' 错误。我已经导入了import { map } from "rxjs/operators";,但仍然没有解决它。我在这个项目上运行 Angular 9.0.2
  • @solarflare,对不起,我的错误,我更新了问题,你需要在地图前添加一个管道运算符
  • 啊,好的,谢谢 - 所以我实际上仍然在 onSubmit 中为 customer 定义不确定。我的实际上是不同的-所以我注销了res而不是customer,因为这给了我一个错误,但是res仍然显示为未定义这可能是因为customer如果直接在@987654332之后登录@ 也未定义!
  • 是的,您是对的,您应该在onSubmit 中记录 res 而不是 customer,当您在 map 运算符中返回之前记录 customer 时,它是否未定义?
  • loadCustomer怎么样,如果你在返回之前添加console.log(customer),那里有值吗?
猜你喜欢
  • 1970-01-01
  • 2020-01-13
  • 2017-09-27
  • 1970-01-01
  • 2019-11-15
  • 2017-01-16
  • 1970-01-01
  • 2019-05-11
  • 1970-01-01
相关资源
最近更新 更多