简体   繁体   English

angular 2-http get返回空数组

[英]angular 2 - http get returns empty array

My Component code: 我的组件代码:

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

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

My HTML Code: 我的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>

My Service Code: 我的服务代码:

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()));

My Backend route: 我的后端路线:

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",
},

My Backend Model Class: 我的后端模型班:

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

My Frontend Model: 我的前端模型:

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

在此处输入图片说明

My http://localhost:3000/product reutrns the json response correctly. 我的http://localhost:3000/product正确地返回了json响应。 But somehow in the HTML, when the page loads everything is empty. 但是以某种方式在HTML中,当页面加载时,所有内容都是空的。
I am only getting one value - empty empty 111 111 我只有一个值- empty empty 111 111

Most of the things are setup fine, I am not sure why the empty HTML when I get the response back from http://localhost:3000/product 大多数事情设置都很好,我不确定为什么从http://localhost:3000/product返回响应时为什么使用空HTML

I better suggest make change in your backend code and try to return json string structure like 我最好建议在您的后端代码中进行更改,并尝试返回json字符串结构,例如

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

that will resolve your issue , without not much code change in front end ie in angular part 这样可以解决您的问题,而无需在前端(即在有角的部分)中进行很多代码更改


if you are not getting sturcture of reponse properly I sugest you make use of this potal : http://json2ts.com/ which helps to convert json string to typscript object. 如果您没有正确地构造响应,我建议您使用此命令: http ://json2ts.com/,它有助于将json字符串转换为典型对象。

for this structure given by you : { "0": { "SKU": "V2620151BR", "MRP": "799" }} 对于您提供的此结构: { "0": { "SKU": "V2620151BR", "MRP": "799" }}

this is typescript object got created. 这是打字稿对象创建。

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

    export interface ProductRoot{
        productDetail: ProductDetail;
    }
}

if you have above kind of structure than your code will be as below (i havent run code at my end but if there is any error please inform it should be like that only ) 如果您具有上述那种结构,那么您的代码将如下所示(我没有运行代码,但是如果有任何错误,请告知它应该只是这样)

 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()));

code in component 组件中的代码

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

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

i suggest not to give same name to propeties , better keep name different - try below code 我建议不要对属性使用相同的名称,最好保持名称不同-尝试以下代码

I am guessing here that your server code is returning json array of product 我在这里猜测您的服务器代码正在返回产品的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()));

component code 组件代码

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

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

You are subscribing to the empty array in your case, because the return is executed before getting all the data. 您正在订购空数组,因为返回是在获取所有数据之前执行的。 That's why it is better to use Promise 这就是为什么最好使用Promise

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

If you want to keep your code, try to create an initial empty product and a real BehaviorSubject and emit the new value, then subscribe to this : 如果要保留代码,请尝试创建一个初始的空产品和一个真实的BehaviorSubject并发出新值,然后预订:

this.initialProduct = EMPTY_PRODUCT;

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

then just before the return this.changeProduct.emit(product); 然后就在返回this.changeProduct.emit(product); and subscribe to the answer instead of the get function : this.changeProduct.subscribe((product) => {doSomething()}; 并订阅答案而不是get函数: this.changeProduct.subscribe((product) => {doSomething()};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM