angular 2 - http get返回空数组

时间:2017-11-29 17:45:13

标签: angular

我的组件代码:

products: Product[];
constructor(private productService: ProductService) { }

ngOnInit() {
    this.productService.getProducts()
        .subscribe(
        (products: Product[]) => {
            this.products = products;
        }
        );
}

我的HTML代码:

                <tr *ngFor="let product of products">
                    <td>
                        <a [routerLink]="['/product-details', product.SKU]">{{ product.SKU }} </a>
                    </td>
                    <td>
                        <a [routerLink]="['/product-details', product.SKU]">{{ product.mrp }} </a>
                    </td>
                </tr>

我的服务代码:

getProducts() {
    return this.http.get('http://localhost:3000/product')
        .map((response: Response) => {
            const products = response.json().obj;

            let transformedMessages: Product[] = [];
            for (let product of products) {
              transformedMessages.push(new Product(product.SKU, product.mrp, 111, 111));
            }
            this.products = transformedMessages;
            return transformedMessages;

            return products;

        })
        .catch((error: Response) => Observable.throw(error.json()));

我的后端路线:

router.get('/', function (req, res, next) {
    Product.find().exec(function (err, products) {
        if (err) {
            return res.status(500).json({
                title: 'An error occurred',
                error: err
            });
        }
        res.status(200).json({
            message: 'Success',
            obj: products        //obj comes from here
        });
    });
});

Response:
{
"message": "Success",
"obj": [
{
"0": {
"SKU": "V2620151BR",
"Batch": "1",
"Folder Number": "85",
"MRP": "799",
"Size": "Free",
"Color": "Yellow",
},

我的后端模型类:

var schema = new Schema({
    sku: { type: String, required: true, unique: true },
    mrp: { type: Number }
});

我的前端模特:

export class Product {
    constructor(
        public SKU: string,
        public mrp: number,
        public selling_price: number,
        public current_inventory: number
    ) { }
}

enter image description here

我的http://localhost:3000/product正确地重新启动了json响应。但不知何故,在HTML中,当页面加载时,一切都是空的 我只得到一个值 - empty empty 111 111

大部分内容都设置正常,当我从http://localhost:3000/product获取回复时,我不确定为什么会出现空白HTML

2 个答案:

答案 0 :(得分:1)

我建议您在后端代码中进行更改并尝试返回类似

的json字符串结构
Response:
{
"message": "Success",
"obj": [
{
"ProductId": "0",
"SKU": "V2620151BR",
"Batch": "1",
"Folder Number": "85",
"MRP": "799",
"Size": "Free",
"Color": "Yellow",
},
}

将解决您的问题,前端没有太多代码更改,即在角度部分

如果你没有得到适当的反应结果,我觉得你使用这个potal:http://json2ts.com/有助于将json字符串转换为typscript对象。

由您提供的此结构:{ "0": { "SKU": "V2620151BR", "MRP": "799" }}

这是创建的打字稿对象。

declare module namespace {
    export interface ProductDetail{
        SKU: string;
        MRP: string;
    }

    export interface ProductRoot{
        productDetail: ProductDetail;
    }
}

如果你的结构类型比你的代码更合适(我没有在我的最后运行代码,但是如果有任何错误请告知它应该只是那样)

 getProducts() : Observable<Array<ProductDetail>>
     {
          return this.http.get('http://localhost:3000/product')
            .map((response: Response) => {
               debugger;//try to debug this part specially response returned 
                        //for server 
               let resproducts:Array<ProductRoot> = response.json().obj;

               let transformedMessages: ProductDetail[] = [];
              for (let product of resproducts) {
                 transformedMessages.push(new ProductDetail(product.productDetail.SKU, product.productDetail.mrp, 111, 111));
             }
              return transformedMessages;
        })
        .catch((error: Response) => Observable.throw(error.json()));

组件中的代码

products: ProductDetail[];
constructor(private productService: ProductService) { }

ngOnInit() {
    this.productService.getProducts()
        .subscribe(
        (products: Product[]) => {
            this.products = products;
        }
        );
}

我建议不要给同一个名字命名,最好保持名字不同 - 试试下面的代码

我在这里猜测你的服务器代码正在返回产品的json数组

 getProducts() 
 {
      return this.http.get('http://localhost:3000/product')
        .map((response: Response) => {
           debugger;//try to debug this part specially response returned 
                    //for server 
           let resproducts:Array<Product> = response.json();

           let transformedMessages: Product[] = [];
          for (let product of resproducts) {
             transformedMessages.push(new Product(product.SKU, product.mrp, 111, 111));
         }
          return transformedMessages;
    })
    .catch((error: Response) => Observable.throw(error.json()));

组件代码

products: Product[];
constructor(private productService: ProductService) { }

ngOnInit() {
    this.productService.getProducts()
        .subscribe(
           (res) => {
               this.products = res;
             }
        );
}

答案 1 :(得分:1)

您正在订阅您的案例中的空数组,因为在获取所有数据之前执行了返回。这就是为什么使用Promise更好的原因

return this.http.get(url)
        .toPromise()
        .then((response) => {doSomething()});

如果您想保留代码,请尝试创建一个初始空产品和一个真实的BehaviorSubject并发出新值,然后订阅:

this.initialProduct = EMPTY_PRODUCT;

changeProduct: BehaviorSubject<Product or any> = new BehaviorSubject(this.initialProduct)

然后在返回this.changeProduct.emit(product);之前订阅答案而不是get函数: this.changeProduct.subscribe((product) => {doSomething()};