Angular2蒙上了JSON结果界面 [英] Angular2 cast a json result to an interface

查看:125
本文介绍了Angular2蒙上了JSON结果界面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Angular2和打字稿,我有JSON从返回的WebAPI,我需要把它变成某种类型的数组。我无法弄清楚如何铸就JSON来我所需要的接口。

Using Angular2 and typescript, I have JSON returned from a webApi and I need to get it into an array of a certain type. I can't figure out how to cast the json to the interface I need.

我喜欢的类型是这样的接口:

My type is this interface:

export interface Country {
    Id: number;
    Name: string;
}

我的模拟返回这个数组:

My mock returns this array:

export var COUNTRIES: Country[] = [
    { "Id": 11, "Name": "US" },
    { "Id": 12, "Name": "England" },
    { "Id": 13, "Name": "Japan" }
];

下面是我的code:
country.service.ts

Here is my code: country.service.ts

@Injectable()
export class CountryService {
    private _http = null;

    constructor(http: Http) {
        this._http = http;
    }

    getCountries() {
        return Promise.resolve(COUNTRIES);
    }
}

然后我这个称呼它:

Then I call it with this:

export class CountryPickerComponent {
    public countries: Country[];

    constructor(private _countryService: CountryService) { }


    getCountries() {
        this._countryService.getCountries().then(data => this.setData(data));
    }

    setData(data) {
        //this.countries = data;
        this.countries = JSON.parse(data);
        var q = 1;
    }

    ngOnInit() {
        this.getCountries();
    }
}  

正如你所看到的,我有一个叫做国家一类变量,它是国家的接口的数组。这按预期工作。 (我知道我不需要那么SetData方法 - 这是用于调试)

As you can see, I have a class variable called countries that is an array of the Country interface. This works as expected. (I know I don't need that setData method - it's for debugging)

接下来,我改变了服务到wepApi调用返回该JSON。

Next, I changed the service to a wepApi call which returns this json.

"[{"name":"England","id":1},{"name":"France","id":2}]"

我改变了的getCountries方法的服务:

I changed the getCountries method in the service to:

getCountries() {
    return new Promise(resolve=>
        this._http.get('http://localhost:63651/Api/membercountry')
            .subscribe(data => resolve(data.json()))
    );
}

使用JSON.parse,我将其转换为一个数组,然后我就可以在angular2使用。有用。它创建具有数据的数组。但它不执行国家接口的数组。

Using JSON.parse, I convert this to an array which I can then use in angular2. It works. It creates the array with the data. But it's not an array implementing the Country interface.

请注意,从JSON字段名都为小写,但接口的属性以大写和I coded到界面开始。其结果是,当我真正的JSON这是行不通的。是否有投这对接口的方式,这应该抛出一个错误,让我知道什么是错的?

Notice that the field names from the JSON are all lower case, but the interface properties starts with an uppercase and I coded to the interface. As a result, when I got the real json it does not work. Is there a way to 'cast' this to the interface, which should throw an error and let me know something is wrong?

许多示例使用在获取地图,如下图所示:

Many examples use map in the get as shown below:

  getCountries() {
        var retVal;

        return new Promise(resolve=>
            this._http.get('http://localhost:63651/Api/membercountry')
                .map(ref => ref.json())
                .subscribe(data => resolve(data.json()))
        );
    }

我无法找到本文档。当我尝试它,我从来没有得到数据,但没有任何错误。没有编译错误,也没有运行时错误。

I can't find documentation on this. When I try it I never get data but there is no error. No compile error and no runtime error.

推荐答案

您可以做一个类型断言你期望通过JSON.parse创建的对象的接口。

You can do a type assertion to the interface you are expecting on the object created by JSON.parse.

 this.http.get('http://localhost:4200/').subscribe((value: Response) => {
    let hero = <ServerInfo>value.json();
  });

但是如果服务器发送你的,因为两个原因不好的对象,这将不会导致任何错误。

However this will not result in any errors if the server sends you bad objects because of 2 reasons.

transpiler不知道服务器将发送。

At compile time the transpiler does not know what the server will send.

目前运行的所有类型的信息将被删除,因为一切都被编译成
JavaScript的。

At runtime all type information is erased since everything gets compiled to javascript.

这篇关于Angular2蒙上了JSON结果界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆