How to Inject Angular2 Http service into es6/7 Class?

前端 未结 4 491
生来不讨喜
生来不讨喜 2020-12-03 21:52

If I use es6/7 (babel - stage 1) instead of TypeScript, how are services, and specifically Http, injected?

Here\'s my component JS:

import {Compone         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-03 22:14

    With babel-plugin-angular2-annotations, you can inject services with constructor parameter type annotations just like TypeScript.

    Install babel plugins:

    npm install -D babel-plugin-angular2-annotations babel-plugin-transform-decorators-legacy babel-plugin-transform-class-properties babel-plugin-transform-flow-strip-types babel-preset-es2015
    

    .babelrc:

    {
      "plugins": [
        "angular2-annotations",
        "transform-decorators-legacy",
        "transform-class-properties",
        "transform-flow-strip-types"
      ],
      "presets": [
        "es2015"
      ]
    }
    

    and voila!

    import {Component, View, CORE_DIRECTIVES, ViewEncapsulation} from 'angular2/angular2';
    import {Http} from 'angular2/http';
    
    @Component({
      selector: 'login'
    })
    @View({
      templateUrl: './components/login/login.html',
      styleUrls: ['components/login/login.css'],
      directives: [CORE_DIRECTIVES],
      encapsulation: ViewEncapsulation.Emulated
    })
    export class Login {
      constructor(http: Http) {
        console.log('http', http);
        this.http = http;
      }
    
      authenticate(username, password) {
        this.http.get('/login');
      }
    }
    

    Note that the type signature is used only for a hint for dependency injection and not used for type-checking.

提交回复
热议问题