我目前有一个工作代码,但我想知道是否有更好的方法在Angular 2中实现关系。以下是我的课程:
import { Picture } from '../picture/picture';
import { Part } from '../part/part';
export class Product {
constructor(
public title: string,
public imageUrl: string,
public description: string,
public price: number,
public productId?: string,
public pictures?: [Picture],
public parts?: [Part]){}
}
//The same code for Part Class:
export class Picture {
constructor(
public name: string,
public pictureUrl: string,
public productId?: string,
public pictureId?: string){}
}
以下是我的product.service,只是为了获得所有产品:
getProducts() {
return this._http.get('http://localhost:3000/product')
.map(response => {
const data = response.json().obj; // from server route
let objs: any[] = [];
for (let i = 0; i < data.length; i++) {
let product = new Product(data[i].title, data[i].imageUrl,
data[i].description, data[i].price, data[i].id,
data[i].pictures, data[i].parts);
objs.push(product);
}
this.products = objs;
})
.catch(error => Observable.throw(error.json()));
}
提前多多感谢。