我
正在将角度 1 转换为角度 2(离子 2(,我创建了这个提供程序来替换服务,但我的本地函数出错。
如何使用 angular2 和 Typescript 声明本地函数?
import { Injectable } from '@angular/core';
@Injectable()
export class PouchSeed {
constructor() { }
function normalizeDoc(doc, id) {
function normalize(doc) {
doc = angular.copy(doc);
Object.keys(doc).forEach(function (prop) {
var type = typeof doc[prop];
if (type === 'object') {
doc[prop] = normalize(doc[prop]);
} else if (type === 'function') {
doc[prop] = doc[prop].toString();
}
});
return doc;
}
var output = normalize(doc);
output._id = id || doc._id;
output._rev = doc._rev;
return output;
}
....
seed(db, designDocs, callback) {
if (!db || !designDocs) {
throw new TypeError('`db` and `design` are required');
}
var local = objMapValues(objMapKeys(designDocs, addDesign), normalizeDoc);
var seedPromise = db.allDocs({include_docs: true, keys: Object.keys(local)})
.then(function (docs) {
var remote = {};
docs.rows.forEach(function (doc) {
if (doc.doc) {
remote[doc.key] = doc.doc;
}
});
var update = Object.keys(local).filter(function (key) {
if (!remote[key])
return true;
local[key]._rev = remote[key]._rev;
return !docEqual(local[key], remote[key]);
}).map(function (key) {
return local[key];
});
if (update.length > 0) {
return db.bulkDocs({docs: update});
} else {
return Promise.resolve(false);
}
})
.then(function (result) {
if (typeof callback === 'function') {
callback(null, result);
}
return Promise.resolve(result);
})
.catch(function (err) {
if (typeof callback === 'function') {
callback(err, null);
}
console.log(err);
return Promise.reject(err);
});
return seedPromise;
};
}
错误:
Typescript Error
Unexpected token. A constructor, method, accessor, or property was expected.
src/providers/pouch-seed.ts
function normalizeDoc(doc, id) {
function normalize(doc) {
从您使用该normalizeDoc
方法的方式来看,它不需要是嵌套函数。因此,您可以将课程更改为:
@Injectable()
export class PouchSeed {
constructor() { }
normalizeDoc(doc, id) {
var output = this.normalize(doc); // <-- note how you call your normalize method
output._id = id || doc._id;
output._rev = doc._rev;
return output;
}
normalize(doc) {
doc = angular.copy(doc);
Object.keys(doc).forEach(function (prop) {
var type = typeof doc[prop];
if (type === 'object') {
doc[prop] = normalize(doc[prop]);
} else if (type === 'function') {
doc[prop] = doc[prop].toString();
}
});
return doc;
}
....
}