Angular 2 HTTP"无法解析' AppService'"

时间:2016-02-12 19:09:48

标签: typescript angular systemjs angular2-services angular2-injection

我尝试将http提供程序导入服务,但是我收到以下错误:

  

无法解析' AppService'(?)的所有参数。确保所有参数都使用Inject进行修饰或具有有效的类型注释以及“AppService”#39;用Injectable装饰。

以下是一些代码段:

<script src="~/es6-shim/es6-shim.min.js"></script>
<script src="~/systemjs/dist/system-polyfills.js"></script>

<script src="~/angular2/bundles/angular2-polyfills.js"></script>
<script src="~/systemjs/dist/system.src.js"></script>
<script src="~/rxjs/bundles/Rx.js"></script>
<script src="~/angular2/bundles/angular2.dev.js"></script>
<script src="~/angular2/bundles/http.dev.js"></script>

<!-- 2. Configure SystemJS -->
<script>
    System.config({
        map: { 'rxjs': 'RCO/rxjs' },
        packages: {
            RCO: {
                format: 'register',
                defaultExtension: 'js'
            },
            'rxjs': {defaultExtension: 'js'}
        }
    });
  System.import('RCO/Areas/ViewOrganization/AngularTemplates/boot')
      .then(null, console.error.bind(console));

boot.ts

import {bootstrap} from 'angular2/platform/browser'
import {HTTP_PROVIDERS} from 'angular2/http'
import 'rxjs/add/operator/map'
import {AppComponent} from  'RCO/Areas/ViewOrganization/AngularTemplates/app.component'
import {AppService} from 'RCO/Areas/ViewOrganization/AngularTemplates/app.service'

bootstrap(AppComponent, [HTTP_PROVIDERS, AppService]);

app.service.ts

import {Injectable} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Observable} from 'rxjs/Rx';

@Injectable()
export class AppService {

    constructor(private http: Http) { }

    // Uses http.get() to load a single JSON file
    getTableData() {
        return this.http.get('...').map((res: Response) => res.json());
    }

}

我试图调用服务器上的控制器,最终将JSON文件加载到数据表中。非常简单的东西,但我加载Http模块的方式似乎是错误的。任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:53)

Seems like you are not using typescript compiler for transpiling files to js, In that case you need to have use @Inject while injecting any dependency inside a component constructor.

import {Injectable, Inject} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Observable} from 'rxjs/Rx';

@Injectable()
export class AppService {
    constructor(@Inject(Http) private http: Http) { }
    // Uses http.get() to load a single JSON file
    getTableData() {
        return this.http.get('...').map((res: Response) => res.json());
    }
}

答案 1 :(得分:25)

另一种方法是将来节省一些打字:

tsconfig.json添加compilerOptions.emitDecoratorMetadata=true

简单tsconfig.json的例子是:

{
  "compilerOptions": {
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true
  }
}

答案 2 :(得分:0)

我遇到了同样的问题,对我来说问题是我在import { HttpModule } from '@angular/http'

中遗失了app.module.ts

答案 3 :(得分:0)

另一种可能的解决方案是您缺少某些polyfill。如果其他运气不好的人都应该尝试添加此polyfill:

import 'core-js/es7/reflect';