无法在Angular 4中推入JSON数组

时间:2018-02-09 14:27:32

标签: javascript arrays json angular

我正在使用JSON对象的会话变量数组来从HTTP URL获取动态数据列表。

这是我的component.ts代码:

import { IProduct } from "../models/iproduct";
import { Component, OnDestroy, OnInit } from '@angular/core';
import { TimerObservable } from "rxjs/observable/TimerObservable";
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[]  ;
  mysessionvariable: IProduct[] ;
  errorMessage: string;
      private alive: boolean;
    private interval: number
  constructor(private _processJsonService: ProcessJsonService) {  
    this.processList = []; 
    this.mysessionvariable = [];
        this.alive = true;
        this.interval = 1000;

  }

  ngOnInit() {
        TimerObservable.create(0, this.interval)
          .takeWhile(() => this.alive)
          .subscribe(() => {
            this._processJsonService.getProcesslist()
              .subscribe(processList => {
            if (processList instanceof Array) {
                this.processList = processList;
                this.mysessionvariable =  this.SaveDataToLocalStorage(processList);
                this.processList = this.mysessionvariable; 
            } else {
                this.processList = [processList];
               this.mysessionvariable =  this.SaveDataToLocalStorage(processList);
               this.processList = this.mysessionvariable; 
            }  

              });
        });
    }

    ngOnDestroy(){
        this.alive = false;
    }

     SaveDataToLocalStorage(data)
{
    var mysessionarray: any[] = Array.of(JSON.parse(localStorage.getItem('session')));
    // Parse the serialized data back into an aray of objects
  // localStorage.setItem('session', JSON.stringify(data));
    // Push the new data (whether it be an object or anything else) onto the array
    //console.log("my mysessionarray is", mysessionarray)
    console.log("my data in push is", data)
    mysessionarray.push(data);
    //localStorage.setItem('session', JSON.stringify(mysessionarray));
    console.log("my data after push is", mysessionarray)
    return mysessionarray;
}
}

这是我的服务:

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[] > {
    let url = 'myURL';
    return this.http.request(url).map(res => res.json());
  }
}

我收到此错误

ERROR TypeError: mysessionarray.push is not a function
at ProductListComponent.SaveDataToLocalStorage (product-list.component.ts:71)
at SafeSubscriber.eval [as _next] (product-list.component.ts:50)
at SafeSubscriber.__tryOrUnsub (Subscriber.js:240)
at SafeSubscriber.next (Subscriber.js:187)
at Subscriber._next (Subscriber.js:128)
at Subscriber.next (Subscriber.js:92)
at MapSubscriber._next (map.js:85)
at MapSubscriber.Subscriber.next (Subscriber.js:92)
at XMLHttpRequest.onLoad (http.js:1591)
at ZoneDelegate.invokeTask (zone.js:421)

请帮忙解决这个问题吗?我错过了一些进口产品吗?或者请问我的代码有什么问题?

此外,如何刷新JSON数组中的数据意味着当添加新的JSON数据时我需要如果我的数组中存在此行只更新其数据,否则添加新行?

1 个答案:

答案 0 :(得分:0)

您正在使用JSON.parse方法将JSON数据转换为Typescript object

mysessionarray = JSON.parse(localStorage.getItem('session'));

但它不会直接转换为数组,因为localStorage.getItem('session')也可能返回JSON对象。

如果您确定只有JSON Array,那么您可以指定

mysessionarray: any[] = Array.of(JSON.parse(localStorage.getItem('session')));

它会收到的数据会有所不同。希望它有所帮助!!