use marked in Angular2

折月煮酒 提交于 2019-12-06 02:08:02

问题


I'm trying to make a simple Markdown inline editor with Angular2. I tryed several approaches but none seems to work. I installed marked with npm and it is now visible in the projects node_modules directory. I can import it and it is recognized by netbeans. Now when ever I use it nothing works and if I open the firefox debuger then i find localhost:3000/marked not found.

I put the markdown converter in a service. Which looks the following:

import { Injectable } from 'angular2/core';

import * as marked from 'marked';

interface IMarkdownConfig {
  sanitize?: boolean,
  gfm?: boolean,
  breaks?: boolean,
  smartypants?: boolean
}

@Injectable()
export class MarkdownService {
  //private md: MarkedStatic;

  constructor() {
    //this.md = marked.setOptions({});
  }

  setConfig(config: IMarkdownConfig) {
   // this.md = marked.setOptions(config);
  }

  convert(markdown: string): string {
    if(!markdown) {
      return '';
    }
    return markdown;
    //return this.md.parse(markdown);
  }
}

used like this everything works fine, except that markdown is not translated. If I uncomment all lines with md it stops working. The component in which I'm using it looks like that:

import {Component, Input, OnInit } from 'angular2/core';
import {RouteParams} from 'angular2/router';

import {MarkdownService}  from '../services/markdown-converter' 


@Component({
  selector: 'my-story',
  templateUrl: 'app/components/story.html',
  bindings: [MarkdownService]
})
export class StoryComponent implements OnInit {
    public html: string;
    private md: MarkdownService;

    constructor(
         private _routeParams: RouteParams, private _converter: MarkdownService) {
         this.html ='';
         this.md = _converter;
    }

    ngOnInit() {
    }

    public updateValue(val:string) {
        if(!val) { return ''; }
        this.html = val;
    }
}

I'm not displaying all the involved files but If there is a file I should provide just ask in the comments. If it is something I didn't get right about Typescript and or Angular2 injection or whatever, any resource of information explaining those concepts is welcome. I have read a lot on the www but it seems that all documents about Angular2 are quite fast outdated.


回答1:


I would import the marked library this way:

import marked from 'marked';

and use it as you do:

@Component({
  selector: 'markdown', 
  template: `
    <div [innerHTML]="convertedData">
    </div>
  `
})
export class MarkdownComponent {
  @Input('data')
  data:string;

  ngOnChanges() { 
    var md = marked.setOptions({});
    this.convertedData = md.parse(this.data);
  }
}

See this plunkr: https://plnkr.co/edit/zUstS3T7IJxjQUVCXiAM?p=preview.

This question could also help you:

  • How to detect async change to ng-content



回答2:


I finally managed to solve my problem.

I mentioned marked in my index.html file twice once to include the script I installed with npm and once I maped the name marked to https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.5/marked.js if I change this to node_modules/marked/marked.min.js it doesn't work anymore and I get strange GET 404 errors for my project files.

Then I had some entrys for marked in my typings.json and tsconfig.json which where suggested on some sites. I removed those. Finally I left the "marked": "^0.3.5" entry in my package.json file. This is how my index.html looks like:

<!DOCTYPE html>
<html>
  <head>
    <base href="/"/>
    <title>SSE</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">    
    <link rel="stylesheet" href="styles.css">

    <!-- 1. Load libraries -->
    <!-- IE required polyfills, in this exact order -->
    <script src="node_modules/es6-shim/es6-shim.min.js"></script>
    <script src="node_modules/systemjs/dist/system-polyfills.js"></script>
    <script src="node_modules/angular2/es6/dev/src/testing/shims_for_IE.js"></script>   

    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>
    <script src="node_modules/angular2/bundles/router.dev.js"></script>
    <script src="node_modules/marked/marked.min.js"></script>
    <!-- 2. Configure SystemJS -->
    <script>
      System.config({
        packages: {        
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        },
        map: {
          marked: 'https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.5/marked.js'
        }
      });
      System.import('app/main')
            .then(null, console.error.bind(console));
    </script>
  </head>
  <!-- 3. Display the application -->
  <body>
    <my-app>Loading... </my-app>
  </body>
</html>

and this is my package.json:

{
  "name": "sse",
  "version": "1.0.0",
  "scripts": {
    "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "lite": "lite-server",
    "typings": "typings",
    "postinstall": "typings install"
  },
  "license": "ISC",
  "dependencies": {
    "angular2": "2.0.0-beta.15",
    "es6-shim": "^0.35.0",
    "marked": "^0.3.5",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.2",
    "systemjs": "0.19.26",
    "zone.js": "0.6.10"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.2.0",
    "typescript": "^1.8.10",
    "typings": "^0.7.12"
  }
}

I found a lot of similar questions and tryed all their answers as well as the one given by Thierry Templier here but for some reason none of them where working for me, or I was not capable of reproducing them. I feel like there should be a typescript install of marked some where but where ever I add it it doesn't work.




回答3:


This project provides some directives for using Markdown with Angular 2. And it is also using the Marked library.

https://github.com/dimpu/angular2-markdown



来源:https://stackoverflow.com/questions/36729100/use-marked-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!