angular2 Typescript中的嵌套函数

时间:2017-03-25 21:17:57

标签: angular typescript ionic2

我正在从角度1迁移到2,并且我在javascript中嵌套了函数:

function normalizeDoc(doc, id) {
    function normalize(doc){...

我删除了“功能”但现在我从打字稿中得到错误。

import { Injectable } from '@angular/core';


@Injectable()
export class PouchSeed {

    constructor(

    ) {
    }

    normalizeDoc(doc, id) {
        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;
    };

错误:

Typescript Error
';' expected.
src/providers/pouch-seed.ts
normalizeDoc(doc, id) {
    normalize(doc) {
        doc = angular.copy(doc);

Typescript Error
Cannot find name 'normalize'.
src/providers/pouch-seed.ts
normalizeDoc(doc, id) {
    normalize(doc) {

Typescript Error
Cannot find name 'angular'.
src/providers/pouch-seed.ts
normalize(doc) {
    doc = angular.copy(doc);

嵌套这样的方法可以吗? 什么与“;”错误?

由于

1 个答案:

答案 0 :(得分:0)

如果您将es2016es2017库添加到编译器中,请在 tsconfig.json 中添加:

  "compilerOptions": {
    "lib": [
      ..., "es2016", "es2017"
    ]
  }

您可以使用对象差价,Object.entries和TypeScript deconstructing

export class PouchSeed {

  constructor() { }

  normalizeDoc(doc, id) {
    const normalize = o =>
      Object.entries(o)
        .map(([key, value]) => ({
          [key]: typeof value === 'object' ? normalize(value) ? typeof value === 'function' : value.toString() : value
        }))
        .reduce((acc, value) => ({ ...acc, ...value }), {});
    return { ...normalize(doc), _id: id || doc._id, _rev: doc._rev };
  };
}