在angular4 / typescript中创建新的Javascript对象,发送json receving json

时间:2017-07-09 16:46:13

标签: javascript arrays json angular typescript

这将是一个很长的帖子,但我需要明确我对服务器和客户端之间的通信的理解。

说我有一个名为cityList:City[] = [];的变量,它被设计为包含城市列表。

The model for `City` is:

    export class City{
  public name: string;

  constructor(name:string){
    this.name = name;
  }
}

我有一个api电话,旨在返回城市列表。这个服务注入了我的通用getService(下面的getservice):

getService(url) {
    var value: any[] = [];
    this.http.get(url)
      .map(
        (response: Response) => {
          const data = response.json()
            .subscribe(
              (mappedData: any[]) => value = mappedData,
              (error) => console.log(error)
            )
              }
      );
    return value;

将对数据采取行动的服务:

import {Injectable, OnInit} from '@angular/core';
import 'rxjs/Rx';

import {City, Neighborhood, Cuisine, Privacy, VenueType, Amenities } from
import {ServerComService} from "./serverComService";
import {cityListUrl, venueFilterDataOptionsUrl} from 'app/backendUrls';

@Injectable()
export class DynamicFormDataService implements OnInit {

  constructor(private serverComService: ServerComService){}

  cityList: City[]= [];
  neighborhood = [];
  cuisine = [];
  privacy = [];
  venueType = [];
  amenities = [];



  cityGet(){

    if(this.cityList.length > 0 ){
      return this.cityList;
    }
    this.cityList = this.serverComService.getService(cityListUrl)
    return this.cityList;
  }

 ngOnInit(){
    this.cityGet();
}

}

在导入中存在一些拼写错误,但是让我们忽略它们,这就是我首先要理解的。

当我想使用cityList数组中的数据时,它是否只是迭代并调用该数组来定位city.name值?

如果我想添加到城市列表数组呢?

我必须打电话给城市建设者, 所以也许是一个以表单数据作为参数的函数,然后

c = new City('Pound Town');
cityList.push(c);

然后是一个调用push或put方法的服务,具体取决于我是在更新还是创建新的。

那么主要和完整的问题是,在此过程中我是否缺少任何跳过转换的内容 Json进入Javascript对象

或Javascript对象到Json?

或者我的总体执行是否正确?设置变量类型是否采用json的字符串并将它们转换为适用于我的客户端代码中的对象的类型?

1 个答案:

答案 0 :(得分:0)

您的代码存在一些问题:

(1)如果在异步操作(例如http请求)中提取该值,则无法返回该值。
您需要返回对值的承诺而不是值本身 类似的东西:

getService(url) {
    this.http.get(url).then(response => {
        // transform response and return it
    }).catch(e => console.log(e));
}

(2)由于getService是异步的,cityGet也无法返回值,所以可能会这样:

cityGet() {
    if(this.cityList.length > 0 ){
        return Promise.resolve(this.cityList);
    }

    return this.serverComService.getService(cityListUrl).then(response => {
        this.cityList = response;
    });
}

(3)在getService中,您收到一个表示json响应的js对象,如果您想拥有City的实例,那么您需要在结果中为每个项创建一个实例:< / p>

getService(url) {
    this.http.get(url).then(response => {
        return response.map(city => Object.assign(new City(), city));
    }).catch(e => console.log(e));
}