Создание моего собственного определения формы в jointjs не работает в angular7 - PullRequest
3 голосов
/ 19 октября 2019

Я использую angular 7 и joint.js, чтобы создать собственное определение формы. Например,

joint.shapes.devs.Model.define("devs.Type",
  {
    size: {
      width: 300,
      height: "auto"
    }
 });

joint.shapes.standard.Rectangle.define('examples.CustomRectangle', {
    attrs: {
        body: {
            rx: 10, // add a corner radius
            ry: 10,
            strokeWidth: 1,
            fill: 'cornflowerblue'
        },
        label: {
            textAnchor: 'left', // align text to left
            refX: 10, // offset text from right edge of model bbox
            fill: 'white',
            fontSize: 18
        }
    }
});






var rect2 = new joint.shapes.examples.CustomRectangle();
var a1 = new joint.shapes.devs.Type(node);

Компиляция кода дает мне две ошибки

Ошибка TS2339: свойство 'Тип' не существует в типе 'typeof devs' Ошибка TS2341: Примеры свойств ''не существует в типе' typeof shape '.

Как бы я решил эту проблему?


Более того, ссылка для клиента определяет метод transitionColor, но он может'не вызывается в paper.on ("link: mouseover", ...., ошибка

Свойство 'transitionColor' не существует для типа 'Link'.

joint.dia.Link.define(
      "devs.Link",
      {
        attrs: {
          line: {
            connection: true
          },
          wrapper: {
            connection: true,
            strokeWidth: 2,
            strokeLinejoin: "round"
          }
        }
      },
      {
        markup: [
          {
            tagName: "path",
            selector: "wrapper",
            attributes: {
              fill: "none",
              cursor: "pointer",
              stroke: "transparent"
            }
          },
          {
            tagName: "path",
            selector: "line",
            attributes: {
              fill: "none",
              "pointer-events": "none"
            }
          }
        ],
        transitionAsync: function (...args) {
          return new Promise(resolve => {
            this.transition(...args);
            this.on("transition:end", () => {
              resolve();
            });
          });
        },
        transitionColor: function (color, { delay = 0, duration = 100 }) {
          return this.prop("attrs/line/stroke", color);
        },
        transitionOpacity: function (opacity, { delay = 0, duration = 100 }) {
          return this.prop("attrs/line/opacity", opacity);
        }
      }
    );


paper.on("link:mouseover", (linkView: any) => {
      const links = this.graph.getLinks();
      links.map(link => {
        if (link === linkView.model) {
          return;
        }
        link.transitionColor(theme.colors.line.inactive, {duration:500});
        link.toBack()
      });
});

1 Ответ

0 голосов
/ 30 октября 2019

Ваша проблема связана с TypeScript, а не с Angular, и, возможно, с типизацией, доступной для библиотеки.

Ваше сообщение об ошибке гласит 'Type' does not exist on type 'typeof devs'. Это означает, что ваша переменная devs не является типизированной, поэтому TypeScript выводит тип динамически из определения переменной:

// devs is not declared this way, but this is just to make the point
const devs = {
  prop1: string;
  prop2: number;
};

// you can add extra properties with the JavaScript square brackets access:
devs['Type'] = function() { ... }

devs['Type']() // <- this call works

devs.Type() // <-- compile time exception: Type is not present in the type.

Чтобы выйти из этой головоломки, вы можете:

  1. Поймите, есть ли проблема с типами, доступными для библиотеки, и загрузите соответствующий файл типизаций (файл .d.ts, полученный из некоторой библиотеки). Это, безусловно, предпочтительный вариант, если кто-то другой удосужился определить сигнатуры типов, потому что ваш код проверяется во время компиляции. Однако, если у вас нет доступа к файлу набора текста, компиляция их по окончании нецелесообразна.
  2. Отказаться от системы типов TypeScript и просто использовать any. Если вы знаете библиотеку, и вам удобно использовать ее в простом JavaScript, вы можете просто объявить, что используемые вами объекты НЕ набраны:
// this out of any class body declares that somewhere in window, a joint object exists, and we don't know anything about it
declare const joint: any;

// or, when calling a subsection of joint with bad or incomplete typings:
const a1 = new (joint.shapes.devs as any).Type(node);
// same meaning, different syntax:
const a2 = new (<any>joint.shapes.devs).Type(node);

// you can just get an untyped reference to devs and use it:
const untypedDevs: any = joint.shapes.devs;
const a3 = new untypedDevs.Type(node);

В общем, вам следуетпопробуйте выучить хотя бы немного TypeScript, потому что это язык, который вы используете сейчас.

Надеюсь, это поможет!

...