2017-09-16 37 views
0

在我的ngOnInit()方法中,我調用數據服務來檢索產品數據。在此調用之後,我立即調用本地方法getProductImages(),以從以前檢索的產品中獲取圖像,但出現getProducts()調用結果的產品Product []數組錯誤未定義。顯然,在調用dataService.getProducts()完成之前調用getProductImages()方法。代碼如下所示。我該如何解決。角度2:HTTP數據由於競爭條件而不存在

export class WelcomeComponent implements OnInit { 
    products: Product[]; 
    productImages: ProductImage[]; 

    constructor(private welcomeService: WelcomeService, 
    private dataService: DataService) { } 

    ngOnInit() { 
    this.dataService.getProductsDb() 
    .then(products => { 
     this.products = products;  
     console.log('WelcomeComponent products = ' + new Date() + 
     JSON.stringify(this.products)) 

     this.getProductImages(); 
     console.log('productImages = ', JSON.stringify(this.productImages)) 
}) 
     // .then(this.dataService.getProductImages();) 
    } 

    private getProductImages() { 
    for(var i=0; i < this.products.length; i++) { 
     this.productImages[i]._id = this.products[i]._id; 
     this.productImages[i].name = this.products[i].name; 
     this.productImages[i].price = this.products[i].price; 
     this.productImages[i].image = this.products[i].image[0]; 
    } 
    } 

} 
+0

你不在您的產品類中有圖像:字符串?如果你這樣做,那麼顯示每個產品的圖像只是

{{product.image}}
。只是想幫助。 –

+0

請向我們展示返回給您的服務的產品json的定義以及onNgInit中的日誌語句的輸出 – GreyBeardedGeek

回答

1

您需要在設置this.products後調用getProductImages()。正在發生的事情是他們在同一時間接電話,而不是一個接一個接電話。你可以用下面的代碼來解決這個問題,我相信:

ngOnInit() { 
this.dataService.getProductsDb() 
.then(products => { 
    this.products = products;  
    console.log('WelcomeComponent products = ' + new Date() + 
    JSON.stringify(this.products)) 


}) 
.then(
    this.getProductImages(); 
    console.log('productImages = ', JSON.stringify(this.productImages)); 
) 
    // .then(this.dataService.getProductImages();) 
} 

然而,我會研究Observables,這是非常有用的。 您的變量將是這樣的:

products: Observable<any>;

productImages: Observable<any>;

然後你的函數可能看起來像:

this.dataService.getProductsDb() 
.map(response => response.json()) 
.subscribe(response => { 
    this.products = response; 
}, 
    error => console.log(error), 
() => { 
    this.getProductImages(); 
    console.log('productImages = ', JSON.stringify(this.productImages)); 
    }); 

你可以閱讀更多的https://github.com/reactivex/rxjshttp://reactivex.io/