简体   繁体   English

Angular 2同时使用打字稿和JavaScript

[英]Angular 2 using both typescript and javascript

I have angular 2 application written on javascript. 我有用JavaScript编写的angular 2应用程序。 I want to migrate it to typescript. 我想将其迁移到打字稿。

JS code is: JS代码是:

(function (app) {
    app.SomeService = ng.core
        .Class({
            constructor: [app.AnotherService, function SomeService(s) {
                this._anotherService = s;
            }],  
            someFunction: function(){
                ...
            }
            .....    
        });
})
(window.app || (window.app = {}));

I want to inject this service into my typescript component. 我想将此服务注入到我的打字稿组件中。 How can I do that? 我怎样才能做到这一点?

I tried to use it like this: 我试图这样使用它:

@Component({...})
export class SomeComponent {
    constructor(public someService: window.app.SomeService) {
    }
}

But it does not work. 但这行不通。

The way I've managed to mix JS and TS is to have a file with the JS, in your case let's say it's src/app.js , with the code you posted above. 我设法混合JS和TS的方法是将文件与JS一起使用,就您而言,假设它是src / app.js,并带有上面发布的代码。

At this point you can do one of two things: 此时,您可以执行以下两项操作之一:

  1. You create a component that is going to use said JS code, something like: 您创建一个将使用所述JS代码的组件,例如:

     import {Component} from "angular2/core"; @Component({ selector: 'app', template: ` <a> <onclick='app()'>When the function is clicked, use app() code</a> , directives: [] }) export class App { constructor(){ } } 

The template is going to depend on what your code is supposed to do. 该模板将取决于您的代码应该做什么。 I often use onClick, but here you have an example of what it might look like: 我经常使用onClick,但是在这里您可以看到一个示例:

  template: `<input value="Select Date" type="text" class="datepicker" onclick ="myCalendar()" >

` `

  1. Another option is to call the JS code from the constructor 另一种选择是从构造函数中调用JS代码

     import {Component} from 'angular2/core'; @Component({ selector: 'app', template: ` <div> </div> `, directives: [] }) export class MyApp { name:string; constructor() { this.name='Angular 2'; app(); } } 

So it depends on what you want to do, and when, as far as I can tell. 因此,据我所知,这取决于您想做什么以及何时进行。 There are people with more experience but I tried to not say anything wrong, and provide code similar to what I have working right now. 有些人有更多的经验,但是我尽量不要说错什么,并提供与我现在正在工作的类似的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM