【发布时间】:2016-05-28 08:59:12
【问题描述】:
我正在使用带有 TypeScript 的 Angular 1.5.x。为了访问远程 API,我使用了 restangular。作为总结,这是我的场景:
我的 API 有以下资源 http://localhost:53384/api/timezones。向该 url 发送带有动词 GET 的请求会返回一个 JSON 数组:
[
{
"code":"Dateline Standard Time",
"name":"(UTC-12:00) International Date Line West"
},
{
"code":"UTC-11",
"name":"(UTC-11:00) Coordinated Universal Time-11"
},
{
"code":"Hawaiian Standard Time",
"name":"(UTC-10:00) Hawaii"
}
]
现在在我的客户端 AngularJs 应用程序中使用 TypeScript:
Restangular 配置为 restangularProvider: restangular.IProvider
restangularProvider.setBaseUrl("http://localhost:53384/api");
客户端使用 typescript 的 TimeZone 对象表示
module app.blocks {
"use strict";
export class TimeZone {
public code: string;
public name: string;
}
}
Factory(restangular.IService) 来包装 restangular all 'timezones' 资源
module app.services {
factory.$inject = ["Restangular"];
function factory(restangular: restangular.IService): restangular.IElement {
return restangular.all("timezones");
}
angular
.module("app.services")
.factory("app.services.TimeZonesRestangular", factory);
}
使用 TimeZonesRestangular 包装其 restangular 功能并将链式承诺返回给以异步方式请求时区的任何人的服务
module app.services {
"use strict";
export interface IStaticDataService {
getTimeZones(): ng.IPromise<app.blocks.TimeZone[]>;
}
class StaticDataService implements IStaticDataService {
constructor(private timeZonesRestangular: restangular.IElement) {
}
public getTimeZones(): ng.IPromise<blocks.TimeZone[]> {
return this.timeZonesRestangular.getList()
.then((timeZones: blocks.TimeZone[]) => {
return timeZones;
}, (restangularError: any) => {
throw "Error retrieving time zones. Status: " + restangularError.status;
});
}
}
factory.$inject = ["app.services.TimeZonesRestangular"];
function factory(timeZonesRestangular: restangular.IElement): IStaticDataService {
return new StaticDataService(timeZonesRestangular);
}
angular
.module("app.services")
.factory("app.services.StaticDataService", factory);
}
最后在控制器中使用服务异步获取“时区”我有这个声明
//..other controller things not relevant for this sample
this.staticDataService.getTimeZones()
.then((timeZones: blocks.TimeZone[]) => {
this.timeZones = timeZones;
});
有 2 个问题:
-
restangular 的类型定义(我使用
tsd install restangular --resolve --save安装)告诉我getTimeZones() 方法中的successCallback 是promiseValue: any[],这很好,因为它确实是一个数组。我认为这将是一个 TimeZone[] 数组,并且 typescript 可以正确编译,因为它接受any[],但是在调试时我看到successCallback 承诺值它不是 TimeZone[] 数组。它具有我所期望的属性(code和name),但它也有许多其他的东西。该数组中的对象如下所示(加上一些函数):{ "code":"Dateline Standard Time", "name":"(UTC-12:00) International Date Line West", "route":"timezones", "reqParams":null, "restangularized":true, "fromServer":true, "parentResource":null, "restangularCollection":false }根据https://github.com/mgonto/restangular/issues/150,我的回复看起来好像是“重新调整的”。对于像我这样的刚接触到restangular的人的可怕描述.. 我应该使用 restangular 类型定义中的什么接口来表示 restangularized
TimeZone[]的数组? 有没有关于如何使用 TypeScript 实现类似功能的示例?
谢谢。
【问题讨论】:
标签: angularjs typescript angular-promise restangular tsd