这将是一篇很长的文章,但我需要清楚地理解我的服务器和客户端之间的通信。
假设我有一个名为 cityList:City[] = [];
的变量,它旨在包含城市列表。
The model for `City` is:
export class City{
public name: string;
constructor(name:string){
this.name = name;
}
}
我有一个 API 调用,旨在返回城市列表。该服务已将我的通用 getService 注入(inject)其中(下面的 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 http 方法的服务,具体取决于我是更新还是创建新方法。
主要和总的问题是,在这个过程中我是否遗漏了一些跳过转换的东西 Json 转换为 Javascript 对象
或者 javascript 对象转为 Json?
或者我的整体执行是否正确?设置变量的类型是否采用 json 字符串并将它们转换为要在客户端代码中使用的对象的正确类型?
最佳答案
您的代码存在一些问题:
(1) 如果在异步操作(例如 http 请求)中获取该值,则无法返回该值。
您需要返回对值的 promise ,而不是值本身。
像这样的东西:
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
的实例,那么您需要为每个实例创建一个实例结果中的项目:
getService(url) {
this.http.get(url).then(response => {
return response.map(city => Object.assign(new City(), city));
}).catch(e => console.log(e));
}
关于javascript - 在 Angular 4/TypeScript 中创建新的 Javascript 对象发送 json 接收 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44998763/