簡體   English   中英

如何在angular 4中聲明和循環遍歷JSON對象數組?

[英]How to declare and loop through a an Array of JSON objects in angular 4?

我有使用HTTP GET動態獲取的JSON對象。

我想將它們保存在數組中,以便以后循環並在瀏覽器中顯示它們。

請怎么做?

無論如何,在Angular 4的數組中保存從URL動態獲取的JSON對象嗎?

這是我的模型:

export interface IProduct {
    deferred_cmsg: number;
    unprocessed_cmsg: number;
    tempacked_cmsg: number;
    status: string;
    process_name: string;
    instance: number;   
}

這是我的服務:

import { Injectable } from '@angular/core';  
import {  
    Http,  
    HttpModule,
    Headers,  
    RequestOptions,  
    Response  
} from '@angular/http'; 
import { HttpClientModule } from '@angular/common/http'; 
import { Observable } from 'rxjs/Rx';  
import 'rxjs/Rx'; //get everything from Rx    
import 'rxjs/add/operator/toPromise';  
import { IProduct } from "../models/iproduct"; 
@Injectable()  
export class ProcessJsonService {  
    constructor(private http: Http) {}  

   getProcesslist(): Observable < IProduct[] > {  
        return this.http.request('http://www.json-generator.com/api/json/get/cpMCFgbCeW?indent=0')
        .map(res => { console.log("I SEE DATA HERE: ", res.json())
            return res.json(); })
        }
   }    

這是我的組件:

import { Component, OnInit } from '@angular/core';
import { IProduct } from "../models/iproduct";
import { Http } from '@angular/http';   
import { ProcessJsonService } from '../models/myjsonprocess';  
import { Observable } from 'rxjs/Rx'; 

@Component({
  selector: 'app-product-list',
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit {  
  pageTitle: string = 'Process List';
  imageWidth: number = 50;
  imageMargin: number = 2;
  showImage: boolean = false;
  listFilter: string = '';
  processList: IProduct[];  
  errorMessage: string;
  myProcessarray: any[];

  constructor(private _processJsonService: ProcessJsonService) {  
    this.processList = []; 
  }

  ngOnInit(): void {  
        this._processJsonService.getProcesslist()
        .subscribe(processList => {
            if (processList instanceof Array) {
                this.processList = processList;
                console.log("souad", processList);
            } else {
                this.processList = [processList];
                console.log("souad aaa", processList);
            }
        });
          setTimeout(function(){
          location.reload();
        },60000);
  }           
}

這是我的html代碼:

<div class='panel panel-primary'>
  <div class='panel-heading'>
    {{pageTitle}}
  </div>
  <div class='panel-body'>
    <div class='row'>
      <div class='col-md-2'>Filter by:</div>
      <div class='col-md-4'>
        <input type='text' [(ngModel)]='listFilter' />
      </div>
    </div>
    <div class='row'>
      <div class='col-md-4'>
        <h4>Filtered by: {{listFilter}} </h4>
      </div>
    </div>
        <div class='table-responsive'>
            <table class='table'
                   *ngIf='processList && processList.length'>
                <thead>
                    <tr>
                        <th>Process Name</th>
                        <th>Process Instance</th>
                        <th>Process Status</th>
                        <th>Temp-acked Messages Number</th>
                        <th>Unprocessed Messages Number</th>
                        <th>Deferred Messages Number</th>
                    </tr>
                </thead>
                <tbody>
                    <tr *ngFor="let process of processList | processFilter:listFilter" >
                        <td>{{ process.process_name}}</td>
                        <td>{{ process.instance  }}</td>
                        <td>{{ process.status }}</td>
                        <td>{{ process.tempacked_cmsg}}</td>
                           <td>{{ process.unprocessed_cmsg}}</td>
                        <td>{{ process.deferred_cmsg }}</td>  
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

另外,如果在URL(hhttp)中添加了新的json,如何刷新數據。

我在組件中使用了重載,但它沒有刷新。 我也在html的ngFor中使用了Async管道,它顯示了錯誤。

請對這些問題有任何幫助嗎?

服務內部存在問題,您不需要return res.json() 如下更新:

getProcesslist(): Observable < IProduct[] > {
    let url = 'http://www.json-generator.com/api/json/get/cpMCFgbCeW?indent=0';
    return this.http.request(url).map(res => res.json());
}

在組件內部,像這樣聲明變量

processList: IProduct[] = []

ngOnInit(): void {  
    this._processJsonService.getProcesslist()
        .subscribe(processList => {
            this.processList = processList;
        });
}

您的html也存在問題,您需要包含> 0

<table class='table' *ngIf='processList && processList.length > 0'>

上面的方法可以使您每次加載頁面時,都將獲取列表並為您存儲。

要定期獲取數據,您可以執行以下操作:

import { Component, OnDestroy, OnInit } from '@angular/core';
import { Observable } from "rxjs";
import { TimerObservable } from "rxjs/observable/TimerObservable";

export class MyComponent implements OnInit, OnDestroy {
    processList: IProduct[] = [];
    private alive: boolean;
    private interval: number

    constructor() {
        this.alive = true;
        this.interval = 10000;
    }

    ngOnInit() {
        TimerObservable.create(0, this.interval)
          .takeWhile(() => this.alive)
          .subscribe(() => {
            this._processJsonService.getProcesslist()
              .subscribe((processList) => {                    
                  this.processList = processList;                                  
              });
        });
    }

    ngOnDestroy(){
        this.alive = false;
    }
}

編輯:

要將每個新的json列表添加到原始列表中,請執行以下操作:

ngOnInit() {
    TimerObservable.create(0, this.interval)
      .takeWhile(() => this.alive)
      .subscribe(() => {
        this._processJsonService.getProcesslist()
          .subscribe((processList) => {
            if (this.processList.length === 0) {
                this.processList = processList;
            } else {
                processList.forEach((item) => { 
                    this.processList.push(item);
                });
            } 
          });
    });
}

這會將每個新的processList添加到原始數組

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM