我正在将应用程序从Angular 1转换为Angular 2+。我想尝试更好地了解服务中如何处理属性。例如:
在Angular 1中,我们定义了以下服务:
function MyService(AnotherService) {
let flags = [];
在Angular 2+中,我们将服务定义为:
@Injectable()
export class MyService {
private flags = [];
constructor(private _anotherService: AnotherService) { }
问题是,我们正在获取失败的测试,因为在Angular 1中,每次将服务注入到测试中时,“标志”状态似乎都重置为空数组,而在Angular 2+中,状态测试之间会保留“标志”。
我一直在TypeScript游乐场玩耍,尝试确定原因。简而言之,每次向Angular 2注入服务时,如何使“标志”重置为空数组,这似乎与Angular 1服务有关?我认为这是正确的吗?
谢谢!
-----更新-----------
这就是测试的样子
fdescribe('Unit: MyService', function () {
let service;
beforeEach(function () {
angular.mock.inject(function (MyService) {
service = MyService;
});
});
// PASS: For Angular 1 and Angular2+
it('should exist', function () {
expect(service).toBeDefined();
});
// PASS: For Angular 1 and Angular2+
it('should create flags', function () {
let id = 1;
let property = 'testProperty';
let value = 'testValue';
service.setFlags(id, property, value);
let flags = service.getFlags();
let foundElement = flags.find((element) => {
return element.id === id;
});
expect(foundElement.property).toBe(value);
});
// PASS Angular 1, FAIL Angular 2+
it('should update flags', function () {
let id = 1;
let property = 'testProperty';
let value = 'testValue';
service.setFlags(id, property, value);
let flags = service.getFlags();
let foundElement = flags.find((element) => {
return element.id === id;
});
let newValue = 'testNewValue';
service.setFlags(id, property, newValue);
expect(foundElement.testProperty).toBe(newValue);
});