2016-02-08 3 views
3

Я разработал несколько угловых компонентов 2. Структура каталога для моего приложения следующая. This is the directory structure of my applicationКак загрузить несколько угловых компонентов из разных папок в один файл index.html?

и я загрузке каждого компонента из index.html в

<script> 
    System.config({ 
    map: { 'rxjs': 'node_modules/rxjs' }, 
    packages: { 
     app: { format: 'register', defaultExtension: 'js' }, 
     'rxjs': {defaultExtension: 'js'}   
    } 
    }); 
    System.import('component_1/app/main') 
     .then(null, console.error.bind(console)); 
</script> 

, что я сделал это, должен быть только один index.html и по каналу, предоставляемому в System.config Я смогу загрузить различные компоненты. Я могу загрузить компоненты, если я размещаю index.html внутри каждой папки компонентов, но я хочу использовать только один index.html для всех компонентов, вызывая main.ts каждого компонента из этого index.html.

Ниже приведены мои данные о кодах.

  1. index.html

<html> 
 
    <head>  
 
    <title>Angular 2 TypeScript App</title> 
 
    <meta charset="utf-8"> 
 
    <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
 
    <meta name="description" content=""> 
 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
 
    <link href="node_modules\bootstrap\dist\css\bootstrap.min.css" rel="stylesheet" /> 
 
    <link href="node_modules\bootstrap\dist\css\style.css" rel="stylesheet" /> 
 
    <!-- 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/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/http.dev.js"></script> 
 
    <!-- 2. Configure SystemJS --> 
 
    <script> 
 
     System.config({ 
 
     map: { 'rxjs': 'node_modules/rxjs' }, 
 
     packages: { 
 
      app: { format: 'register', defaultExtension: 'js' }, 
 
      'rxjs': {defaultExtension: 'js'}   
 
     } 
 
     }); 
 
     System.import('component_1/app/main') 
 
      .then(null, console.error.bind(console)); 
 
    </script> 
 

 
    </head> 
 

 
    <!-- 3. Display the application --> 
 
    <body> 
 
    <my-app>Loading...</my-app> 
 
    </body> 
 

 
</html>

2.main.ts

import {bootstrap} from 'angular2/platform/browser' 
import {HTTP_PROVIDERS} from 'angular2/http'; 
import 'rxjs/add/operator/map'; 
import {AppComponent} from './app.component' 

bootstrap(AppComponent, [ 
    HTTP_PROVIDERS 
]); 

3.app.component.ts

import {Component} from 'angular2/core'; 
 
import {NgSwitch, NgSwitchWhen, NgSwitchDefault,NgFor} from 'angular2/common'; 
 
import {Http, Response} from 'angular2/http'; 
 
import {Observable} from 'rxjs/Rx'; 
 
import { DataService } from '../app/services/data.service'; 
 

 
@Component({ 
 
    selector: 'my-app', 
 
    providers: [DataService], 
 
    template: '<h1>{{record.data}}</h1>', 
 
    directives: [NgSwitch, NgSwitchWhen, NgSwitchDefault] 
 
}) 
 
export class AppComponent { 
 
    public record;  
 
    constructor(private dataService: DataService) { } 
 
    ngOnInit() {   
 
     this.dataService.getData() 
 
     .subscribe((customers:any[]) => { 
 
      this.record = customers; 
 
     }); 
 
    } 
 
}

4.data.service.ts

import { Injectable } from 'angular2/core'; 
 
import { Http, Response } from 'angular2/http'; 
 
import 'rxjs/add/operator/map'; 
 

 
@Injectable() 
 
export class DataService { 
 
    constructor(private http: Http) { }  
 
    getData() { 
 
     return this.http.get('../../uicomponent.json') 
 
         .map((res: Response) => res.json()); 
 
    } 
 
}

Я перепробовал все методы, но мой index.html не перенаправлять моим main.ts в загрузите мой компонент.

ответ

3

Вы должны определить каждую component_* папки в конфигурацию SystemJS:

<script> 
    System.config({ 
    map: { 
     'rxjs': 'node_modules/rxjs' 
    }, 
    packages: { 
     'component_1': { format: 'register', defaultExtension: 'js' }, 
     'component_2': { format: 'register', defaultExtension: 'js' }, 
     (...) 
     'rxjs': {defaultExtension: 'js'}   
    } 
    }); 
    System.import('component_1/app/main') 
    .then(null, console.error.bind(console)); 

Таким образом, вы будете иметь возможность использовать component_* (например component_1 в вашем импорте).

Если вы хотите сохранить свою конфигурацию и быть в состоянии использовать все компоненты, вы должны переместить component_* папки в папке app ...

+0

Я попробовал ваш code..but его до сих пор не работает –

+0

Я обновил мой ответ. Вам нужно определить каждую папку 'component_ *' в вашей конфигурации SystemJS ... –

+0

, используя ваш код .. работает. Но теперь JSON-файл не получает retiredved..it показывает ошибку, поскольку ресурс не найден. 040 .. –