如何在Angular 2中使用外部Web组件?

时间:2015-12-22 15:55:33

标签: angular web-component

我正在试图弄清楚其他人(我的应用程序外部)开发的Web Components如何在我的应用程序中使用。 我有一个有用的组件,我想在我的AppWithComponent中使用它。 UsefullComponent(UsefullComponent.js)存储在名为“componentsLib”的目录中,而我的应用程序代码存储在名为“myApp”的目录中。 我还有我的index.html导入'myApp'。 整个事情编译(我使用TypeScript),但在运行时我得到一个错误'GET http://127.0.0.1:8080/componentsLib/UsefullComponent 404(未找到)'。 知道我做错了什么?

这里是代码

UsefullComponent.ts

import {bootstrap, Component, FORM_DIRECTIVES, 
   CORE_DIRECTIVES, Input} from 'angular2/angular2';

@Component({
    selector: 'usefull-component',
    providers: [],
    template: `
        <div>
            <h2>My manifesto</h2>
            <h3>{{manifesto}}</h3>
        </div>
        `,
    styleUrls: [],
    directives: [FORM_DIRECTIVES, CORE_DIRECTIVES]
})
export class UsefullComponent { 
    public manifesto: string = 'I am a very usefull component';
}

AppWithComponent.ts

import {bootstrap, Component, FORM_DIRECTIVES, 
        CORE_DIRECTIVES, provide} from 'angular2/angular2';
import {UsefullComponent} from '../../componentsLib/UsefullComponent';

@Component({
    selector: 'my-app-with-comp',
    providers: [UsefullComponent],
    template: `
        <div>
            <h1>I use components</h1>
            <usefull-component></usefull-component>
        </div>
        `,
    styleUrls: [],
    directives: [FORM_DIRECTIVES, CORE_DIRECTIVES, UsefullComponent]
})
class AppWithComponent { 
    public niceComponent: UsefullComponent;

    constructor(inComponent: UsefullComponent) {
        this.niceComponent = inComponent;
    }
}
bootstrap(AppWithComponent);

的index.html

<html>
<head>
<title>Components</title>
<script src="../node_modules/es6-shim/es6-shim.js"></script>
<script src="../node_modules/systemjs/dist/system.src.js"></script>
<script src="../node_modules/angular2/bundles/angular2.dev.js"></script>

<script>
System.config({
        packages: {'myApp': {defaultExtension: 'js'}}
});
      System.import('myApp/myAppWithComp');
</script>
</head>
<body>
<my-app-with-comp>loading...</my-app-with-comp>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

  1. 根据我的知识,我们应该在文件myApp / myAppWithComp中添加以下两行 自举(AppWithComponent);自举(UsefullComponent);
  2. 删除bootstrap(AppWithComponent);来自AppWithComponent.ts文件
  3. 并在index.html文件中添加<div>标记,如下所示

    <body><div><my-app-with-comp>loading...</my-app-with-comp></div></body>
    

答案 1 :(得分:0)

我在代码中看到的唯一错误是组件lib的路径。检查您是否将UsefullComponent.js放在/componentsLib/UsefullComponent.js