2017-08-04 28 views
0

我已經成功實現了這無數次,但我必須在這裏丟失一些東西。我的ngOnInit()函數調用DataService並返回一個產品,如下所示。Angular 2:數據沒有出現在模板中

@Component({ 
    selector: 'app-product-card', 
    templateUrl: './product-card.component.html', 
    styleUrls: ['./product-card.component.css'] 
}) 
export class ProductCardComponent implements OnInit { 
    product: Product; 

    constructor(private dataService: DataService, private route: 
ActivatedRoute) { } 

    ngOnInit() { 
    this.getProduct(); 
    } 

    getProduct() { 
    this.route.params.subscribe(params => { 
    let id = params["id"]; 

     this.dataService.getProduct(id).subscribe((product: Product) => { 
     this.product = product; 
     console.log("ProductCardComponent.product = " + 
JSON.stringify(this.product)); 
     }) 
    }) 
    } 

} 

但產品未在模板中顯示:

<div class="container-fluid"> 
    <div class="col-sm-12"> 
    <div *ngIf="product"> 
     <div class="col-sm-1"></div> 
     <div class="col-sm-5"> 
     <p>{{product.name}}</p> 
     <p>{{product.price}}</p>   
    </div> 

     <div class="col-sm-5"> 
     fadfasdfadfasdf 
     </div> 
    </div> 
    </div> 
</div> 

控制檯日誌:

ProductCardComponent.product = [{"_id":"59809d53734d1d58c9ad47f8","producttype":"washer","name":"Bosch SHE3AR75UC 24 Built-In Dishwasher - Stainless Steel","brand":"Bosch","model":"MVWX655DW","price":539,"list_price":699,"description":"Bosch Ascenta dishwasher SHE3AR75UC offers outstanding Bosch quietness, efficiency and a rich feature set as a superior alternative to all-plastic tub dishwashers. Our exclusive stainless steel wash tub with a polypropylene base makes purchasing an easy choice when it comes to deciding on features, quietness, and value.","rating":4,"item_no":"637743","special_value":true,"warranty":"ANSI Certified,CSA Certified","specification":{"lowes_exclusive":false,"color":"White","high_efficiency":true,"automatic_load_balancing":true,"product_capacity":"4.3 cu ft","large_items_cycle":true,"exclusive_cycle":"PowerWash","maximum_spin_speed":"660","water_levels":"Auto-sensing","number_of_rinse_cycles":"2"},"image":["bosch3.jpg","maytagBravoWasher2.jpg","maytagBravoWasher3.jpg","maytagBravoWasher4.jpg"],"feature":["Large 4.8 cu. ft. oven capacity with space for dinner and dessert","Versatile cooktop with multiple element options up to 1,800 watts","Bake Assist Temp presets make cooking even more convenient"]}] 
+0

在此聲明中記錄到控制檯的是什麼? console.log(「ProductCardComponent.product =」+ JSON.stringify(this.product)); – cobolstinks

+0

是否已達到console.log行? –

+0

達到了console.log。該產品已記錄到控制檯。 – koque

回答

1

從您的控制檯登錄好像你所得到的是一個array,而不是一個object。所以你將不得不抓住第一個元素並分配。嘗試這個。

this.product = product[0];