【问题标题】:Ionic 2 Load items from Promise in ngOnInitIonic 2 在 ngOnInit 中从 Promise 加载项目
【发布时间】:2017-05-01 00:18:39
【问题描述】:

我有 home.ts,它正在调用 service.ts 从存储中加载项目。

export class HomePage {

  products;

  ionViewDidEnter() {
    this.products = this.productService.products;
  }

  ngOnInit(){
      this.productService.fetchProducts();                                    
      this.products = this.productService.products;
  }
}

export class ProductService{ 

  products;

  fetchProducts(){    
    this.storage.get('products') // returns a promise which returns data or error    
      .then(
        (products) => {
        // assign to this.expenses only if not null. When first //strt, can be null. If null, assign empty array []
          products? this.products = products : this.products = [];                                            
          console.log("fetch Products:" + this.products);
          return this.products;
      })  
      .catch(
        err => console.log(err)
      );          
  }

然后我渲染home.html 中的项目。 问题是,当应用程序启动时,项目不会在第一次显示。但是,如果我导航到另一个屏幕并返回 home.ts,这些项目就会恢复正常。我知道这是因为 ionViewDidEnter 并且可能是第一次, fetchProducts 中的承诺是异步的。但是如何让项目首次在ngOnInit 上列出?

【问题讨论】:

标签: angular promise ionic2


【解决方案1】:

处理异步问题的一种方法是在回调中执行操作:

ngOnInit(){
      this.productService.fetchProducts()
        .then((res)=>{
          this.products = this.productService.products;
        });                              
}

您还应该在此处添加return 声明:

fetchProducts(){    
    return this.storage.get('products') // returns a promise which returns data or error    
      .then(..

这是一个笨拙的例子:http://plnkr.co/edit/ONOg4FChJpCG81gM7Vlt?p=preview

【讨论】:

  • 它可以用于渲染 home.ts,但是 productService 中的产品将是未定义的......
  • @Jason 我已经更新了我的答案,但它也不应该在服务中未定义..
  • 天哪!有效!最重要的是,我更了解 Promises 和异步编程
【解决方案2】:

如我所见,您可以通过两种不同的方式来实现...

首先修改方法,以便 typescript 理解它返回带有产品列表的承诺:

fetchProducts(): Promise<Array<any>> {
  // ...
}

1) 预加载信息一次:因此您只需调用一次fetchProducts 方法(可能在启动时)以便将产品加载到内存中,然后您将使用products属性获取数据

// In your app.component.ts
@Component({
    templateUrl: 'app.html'
})
export class MyApp {

    public rootPage: any; // Don't assign the page here yet

    constructor(private platform: Platform,
                private productService: ProductService) {
        this.platform.ready().then(() => {
            // ...

            this.productService.fetchProducts().then(() => {
                this.rootPage = HomePage;
            });
        });
    }

然后在主页中,由于数据已经在内存中,您可以使用服务中的products 属性:

export class HomePage {

  products;

  ionViewDidEnter() {
    this.products = this.productService.products;
  }

}

2) 每次用户进入首页时从存储中获取商品:

    export class HomePage {

      products;

      ionViewDidEnter() {
        this.productService.fetchProducts().then((products) => {
          this.products = this.productService.products;
        });   
      }

    }

【讨论】:

  • 谢谢你seba!
猜你喜欢
  • 1970-01-01
  • 2019-12-12
  • 1970-01-01
  • 2017-05-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多