【问题标题】:Having trouble saving data from an observable in Angular从 Angular 中的 observable 保存数据时遇到问题
【发布时间】:2020-10-04 18:59:23
【问题描述】:

我有来自可观察对象的数据,我试图将其保存到变量中以在模板中使用,我可以看到在可观察对象范围内保存到 this.products 的数组或对象中返回的数据,但是,当我在执行 observable 后检查 this.products 时,它显示为一个空数组。这是我正在使用的代码: 在我的组件中:

  title = 'ngProducts';
  newProduct: any;
  products: any = [] ;
  selectedProduct: any;
  // tslint:disable-next-line:variable-name
  constructor(private _httpService: HttpService) {  }
  // tslint:disable-next-line:use-lifecycle-interface
  ngOnInit() {
    this.newProduct = {details: '', category: '', brand: ''};
    // tslint:disable-next-line:no-unused-expression
    this.selectedProduct;
  }
  getProductsFromService() {
    const observable = this._httpService.getProducts();
    // observable.subscribe(data =>  console.log('this is the observable data: ',  data));
    observable.subscribe(data =>  this.products = data);
    console.log('this is after fetching products: ', this.products);
  }

当我控制台记录可观察对象中的数据时,我得到了对象数组,但是当我尝试将其保存到 this.products 时,它不会保存。所以“获取后”控制台日志只显示一个空数组。

【问题讨论】:

  • 变量this.products是异步赋值的。它不能被同步访问。任何依赖它的语句(如console.log)都必须在订阅中。
  • 仅供参考,您应该拥有那么多行禁用规则;编写规则想要的代码(生命周期接口,未使用的表达式)或为您要编写的内容(变量名)正确配置。

标签: arrays angular object observable


【解决方案1】:

在订阅异步中返回的 observable 的值,并且您尝试在返回值之前访问它。要“获取值后”控制台日志,请将其移动到订阅中。

getProductsFromService() {
    const observable = this._httpService.getProducts();
    observable.subscribe(data => {
      this.products = data,
      console.log('this is after fetching products: ', this.products);
    });
  }

【讨论】:

    【解决方案2】:

    一个 observable 是异步的,这意味着 subscribe() 中的代码执行只在 HTTP 调用完成后运行,而下面的 console.log 立即运行。这意味着 this.products = data 行在执行 console.log 之前不会运行。

    除此之外,代码看起来还不错,那么您遇到了什么问题?您是否因为在前端期待产品而收到错误?你总是可以在前端添加一个 *ngIf="products.length>0" 来解决这个问题。

    【讨论】:

    • 我想我需要看看我的模板是否拉取了产品,我以为我没有得到任何产品,因为 this.products 的数组是空的。试过之后我会更新。
    猜你喜欢
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 2011-12-30
    • 1970-01-01
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多