找不到Angular2 http服务

nos*_*ock 5 dependency-injection typescript angular

无法获得一个简单的http服务在angular2中工作.出于某种原因,我刚刚获得404服务.它还不包含任何功能,但我似乎DI不起作用.

一旦我在引导应用程序时添加TestService,我就会得到以下内容.获取http://127.0.0.1:8080/testService 404(未找到)

的index.html

<!DOCTYPE html>
<html lang="en-GB">
    <head>
        <title>AngularJS 2 Tutorial Series</title>
        <script src="https://code.angularjs.org/2.0.0-beta.0/angular2-polyfills.js"></script>
        <script src="https://code.angularjs.org/tools/system.js"></script>
        <script src="https://code.angularjs.org/tools/typescript.js"></script>
        <script src="https://code.angularjs.org/2.0.0-beta.1/Rx.js"></script>
        <script src="https://code.angularjs.org/2.0.0-beta.1/angular2.dev.js"></script>        
        <script>
            System.config({
                transpiler: 'typescript',
                typescriptOptions: { emitDecoratorMetadata: true }
            });
            System.import('./app/app.ts');
        </script>
    </head>
    <body>

        <my-app>loading...</my-app>

    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

app.ts

import {bootstrap} from 'angular2/platform/browser';
import {Component} from 'angular2/core';
import {Injectable} from 'angular2/core'
import {TestService} from 'testService';

@Component({
    selector: 'my-app',
    template: '<h1>My First Angular 2 App</h1>',
})

class AppComponent {
}

bootstrap(AppComponent, [TestService]);
Run Code Online (Sandbox Code Playgroud)

TestService.ts

import {Http} from 'angular2/http';
import {Injectable} from 'angular2/core';

@Injectable()
export class TestService {
    constructor(public http: Http){        
    }
}
Run Code Online (Sandbox Code Playgroud)

neb*_*lae 14

我刚碰到这个,通过添加脚本引用来修复它:http包:

<script src="node_modules/angular2/bundles/http.dev.js"></script>
Run Code Online (Sandbox Code Playgroud)

记住我在实现路由后添加了类似的资源后尝试了.希望这有助于其他人!


Bro*_*cco 0

您需要Http通过将其作为提供者提供来进行添加。有两种方法可以实现此目的:

1) 在全局级别,您可以在引导应用程序时指定:

bootstrap(AppComponent, [TestService, Http]);
Run Code Online (Sandbox Code Playgroud)

2)在您尝试使用它的组件内部:

@Component({
  ...
  providers: [Http]
})
public class ...
Run Code Online (Sandbox Code Playgroud)

注意,当您作为提供者提供它时,您还必须import/ Http。require这将允许 Angular 的 DI 辨别将要注入的内容。