【发布时间】:2016-01-28 12:25:11
【问题描述】:
我有一个在 TypeScript 中创建的 Angular Service 类,我这个服务有一个加载方法。这个特定的服务,它正在加载的列表实际上是硬编码的,所以我不需要从任何后端服务加载它。我希望 load 方法返回一个承诺,因为我希望服务看起来像我在课堂上拥有的其他数据服务。
这是我拥有的数据服务
module MyApplication.Data {
export interface IDestinationService {
load(): ng.IPromise<Array<MyApplication.Models.Destination>>;
}
export class DestinationService implements IDestinationService {
items: Array<MyApplication.Models.Destination>;
constructor($http: ng.IHttpService, private $q: ng.IQService) {
this.items = new Array<MyApplication.Models.Destination>();
this.items.push(new MyApplication.Models.Destination());
this.items.push(new MyApplication.Models.Destination());
this.items[0].Id = 2;
this.items[0].Description = 'Item 1';
this.items[1].Id = 3;
this.items[1].Description = 'Item 2';
}
load(): ng.IPromise<Array<MyApplication.Models.Destination>> {
var defer = this.$q.defer();
defer.resolve(this.items);
return defer.promise;
}
}
}
根据我的阅读,这应该可以使服务正常工作。它会返回一个promise,但是当它返回时promise会立即被解析,所以then方法应该被触发。
我有一个 Jasmine 测试类,如下所示:
module MyApplication.Tests {
describe('Data', () => {
describe('Destination', () => {
var $http: ng.IHttpService;
var $httpBackend: ng.IHttpBackendService;
var $q: ng.IQService;
beforeEach(inject((_$http_: ng.IHttpService, _$httpBackend_: ng.IHttpBackendService, _$q_: ng.IQService) => {
$http = _$http_;
$httpBackend = _$httpBackend_;
$q = _$q_;
}));
describe('', () => {
var results: Array<MyApplication.Models.Destination>;
beforeEach((done) => {
var service = new MyApplication.Data.DestinationService($http, $q);
service.load()
.then((result) => {
results = result;
done();
});
});
it('Returns Planning Brokers list', () => {
expect(results.length).toBe(2);
});
});
});
});
}
但是当我运行这个测试时,我从 Jasmine 收到了一个异步超时错误,因为 then 方法永远不会触发。我怎样才能让它正常工作。
【问题讨论】:
标签: javascript angularjs typescript angular-promise