2017-01-26 50 views
1

我已經降級了用Angular2 + Typescript編寫的組件。現在我想在簡單的角度1應用程序中使用它,但從Typescript編譯的js文件使用的是'導入',我從瀏覽器中獲得它不受支持。我錯過了什麼?使用Typescript編寫降級angular2組件。如何將它導入到用es5編寫的angular 1項目中?

這是一個簡單的角2組元:

import { Component, OnInit } from '@angular/core'; 

@Component({ 
    selector: 'hello-world', 
    template: ` 
    <p> 
     hello from angular 2! 
    </p> 
    `, 
    styles: [] 
}) 
export class HelloWorldComponent implements OnInit { 

    constructor() { } 

    ngOnInit() { 
    } 


} 


import * as angular from 'angular'; 
import { downgradeComponent } from '@angular/upgrade/static'; 

angular.module('dannyApp', []) 
    .directive(
    'helloWorld', 
    downgradeComponent({component: HelloWorldComponent}) as angular.IDirectiveFactory 
); 

這在簡單angular1應用特林使用此角度2成分以上:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script> 
    <script src="dist\out-tsc\app\hello-world\hello-world.component.js"></script> 

    <script> 
     angular.module('app', []) 

     .controller('FrameController', ['$injector', function($injector) { 
      var vm = this; 
      vm.message = 'Hello from angular 1'; 

     }]); 

    </script> 

    <title>Title</title> 
</head> 
<body ng-app="app"> 

<div id="body"> 
    <div ng-controller="FrameController as vm"> 
    {{vm.message}} 
    </div> 
    <!-- the angular 2 componenet --> 
    <hello-world></hello-world> 
</div> 

</body> 
</html> 

瀏覽器錯誤: 未捕獲的SyntaxError:意外上線令牌進口 :

import { Component } from '@angular/core'; 
+0

在向html添加require.js之後,現在我得到另一個錯誤:模塊名稱「@ angular/core」尚未加載上下文:_。使用require([]) – AngularOne

+0

不知道還有什麼我需要添加到我的角1應用程序。 angualr2組件的文件需要更多的?任何人做到了這一點,併爲他工作? – AngularOne

回答

1

確保您已將您的Typescript組件編譯爲ES5。 你的代碼看起來像ES6/Typescript。

檢查您的tsconfig.json並確保目標:「es5」。

+0

在es5中找到該文件。但現在有關於 的錯誤'require'未定義 – AngularOne

+0

添加'require.js'並且它有幫助。但現在意味着什麼:模塊名稱「@ angular/core」尚未加載上下文:_。使用require([]) 從哪裏得到? – AngularOne

相關問題