使用Angular将HTTP数组值从服务导入组件

时间:2017-11-03 11:48:10

标签: javascript arrays json angular http

我目前正在尝试使用Angular构建应用程序,我有一个服务,它从在线资源中获取数据数组。我想让这个数组在其他组件中可用,但我不确定如何将日期传递给它们。

目前我的服务代码如下所示:

import { Component } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { Injectable } from '@angular/core';

import { Bundle } from './bundle';

import 'rxjs/add/operator/map';


@Injectable()
export class OrderInfo {

  private apiUrl = 'http://dev.assured.api.appdatasite.com/catalog';
  bundlelist: any = {};
  products: any = {};
  selectedBundle: Bundle;

    constructor(private http: Http){
        this.getBundles();
        this.getProducts();
        this.getData();
    }

    getData() {
        const auth = btoa("usernamevalue:passwordvalue");
        const h = new Headers();
        h.set('Authorization', 'Basic ' + auth);
        return this.http.get(this.apiUrl, {headers: h})
            .map((res: Response) => res.json())
    }

    getBundles() {
        this.getData().subscribe(bdata => {
            this.bundlelist = bdata.data.bundles;
            console.log(this.bundlelist);
        })
    }


    getProducts() {
        this.getData().subscribe(pdata => {
            this.products = pdata.data.products;
            console.log(this.products);
        })
    }

    onSelect(bundledata: Bundle): void {
        this.selectedBundle = bundledata;
    };

}

我试图通过的数组是“bundlelist”和“products”。我正在尝试将捆绑数据传递给以下组件:

import { Component, Input, OnInit } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';

import { Bundle } from './bundle';
import { Peripherals } from './peripherals';
import { OrderInfo } from './order.service';

@Component({
  selector: 'my-order',
  template: `
      <h1>Select Bundle</h1>
      <ul class="bundles">
        <li *ngFor="let bundledata of Bundle"
        [class.selected]="bundledata === selectedBundle"
          (click)="onSelect(bundledata)" >
          <h2>{{bundledata.id}}: {{bundledata.name}}</h2>
          <p>{{bundledata.description}}</p>
        </li>
      </ul>
      <bundle-detail [bundle]="this.selectedBundle"></bundle-detail>      
  `,
  providers: [OrderInfo]
})

export class OrderComponent {
    constructor(private orderInfo: OrderInfo) { }

    Bundle: BundleList[];

    getBundles(): void {
        this.orderInfo.getBundles().then(bundlelist => this.bundlelist = bundlelist);
        console.log('unga')
      }

   ngOnInit(): void {
    this.getBundles);
  }  

}

阵列数据排列如下:

{
    "data": {
        "adverts": [],
        "bundles": [{
            "id": "1",
            "name": "Bronze Bundle",
            "price": {
                "installation": "99.99",
                "recurring": "23.99"
            },
            "products": ["1", "2", "3", "4", "9", "10", "15", "15"]
        }, {
            "id": "2",
            "name": "Silver Bundle",
            "price": {
                "installation": "99.99",
                "recurring": "23.99"
            },
            "products": ["1", "2", "2", "2", "2", "4", "9", "10", "15", "15"]
        }, {
            "id": "3",
            "name": "Gold Bundle",
            "price": {
                "installation": "99.99",
                "recurring": "25.99"
            },
            "products": ["1", "2", "4", "5", "9", "10", "15", "15"]
        }, {
            "id": "4",
            "name": "Build Your Own Bundle",
            "price": {
                "installation": "49.99",
                "recurring": "9.99"
            },
            "products": ["1", "10"]
        }],
        "products": [{
            "id": "1",
            "name": "Product 1",
            "price": {
                "upfront": null,
                "installation": "0.00",
                "recurring": "0.00"
            }
        },  {
            "id": "3",
            "name": "Product 3",
            "price": {
                "upfront": "132.00",
                "installation": "9.60",
                "recurring": "2.75"
            }
        }, {
            "id": "4",
            "name": "Product 4",
            "price": {
                "upfront": "60.00",
                "installation": "9.60",
                "recurring": "1.25"
            }
        }, {
            "id": "2",
            "name": "Product 2",
            "price": {
                "upfront": "60.00",
                "installation": "9.60",
                "recurring": "1.25"
            }
        },{
            "id": "5",
            "name": "Product 5",
            "price": {
                "upfront": "228.00",
                "installation": "9.60",
                "recurring": "4.75"
            }
        }, {
            "id": "6",
            "name": "Product 6",
            "price": {
                "upfront": "96.00",
                "installation": "9.60",
                "recurring": "2.00"
            }

        }]
    }
}

从控制台日志可以看到,数组数据肯定会传递给服务,但我无法在订单组件中显示无序的值列表。

如果有人能让我知道我在哪里出错,那么我真的很感激。

3 个答案:

答案 0 :(得分:1)

假设没有语法错误(因为如果您的代码完全是您在上面发布的,那么它应该有语法错误)

this.orderInfo.getBundles().then(bundlelist => this.bundlelist = bundlelist);

您要将数据存储在this.bundlelist(您忘了定义?)和模板中:

<li *ngFor="let bundledata of Bundle" ...>

您使用Bundle(已定义)

您的代码应该是

//Template
<li *ngFor="let bundledata of Bundle" ...>

//TS
Bundle: BundleList[];

//Template
<li *ngFor="let bundledata of bundlelist" ...>

//TS
bundlelist: BundleList[]; 

答案 1 :(得分:1)

我认为其中一种方法如下 -

在OrderInfo中的

- getBundles函数我会返回observable本身

getBundles() {
        this.getData().map(bdata => {
            console.log(this.bundlelist);
            return bdata.data.bundles;
        })
    }

在OrderComponent中 - getBundles函数 -

getBundles(): void {
    this.orderInfo.getBundles().subscribe((bundlelist) => this.Bundle = bundlelist);
    console.log('unga')
}

与getProducts函数相同。

如果您想提供预先获取的数据,您可以将其保存在服务中,检查它是否可用并且可以从中获取Observable。

希望它有所帮助。

答案 2 :(得分:0)

根据YounesMAbhay的答案稍微更改了代码。现在,获取数组的代码为

 getData() {
    if (this.data) {
        return this.data;
    }
    const auth = btoa("anthony.chambers@vdomain.co.uk:password1");
    const h = new Headers();
    h.set('Authorization', 'Basic ' + auth);
    this.data = this.http.get(this.apiUrl, {headers: h})
        .map((res: Response) => res.json())
    return this.data;
}

getBundles() {
    this.bundlelist = [];
    this.getData().subscribe(bdata => {
        for (let key in bdata.data.bundles) {
            this.bundlelist.push(bdata.data.bundles[key]);
        }
        return this.bundlelist;
    });
    return this.bundlelist;
}

并将其拉入组件的代码是:

export class OrderComponent {
    constructor(private orderInfo: OrderInfo) { }

    Bundle: [];

    getBundles(): void {
       this.Bundle = this.orderInfo.getBundles();
    }

   ngOnInit(): void {
    this.getBundles();
  }  

}

感谢你们两位的帮助。这现在似乎正常运作