Angular2 Http模块生成404未找到错误

时间:2016-07-18 12:00:36

标签: angular asp.net-core-1.0

我使用Angular2 beta 17(最新版本)和ASP.NET核心1 MVC应用程序,我尝试使用http如下:

import {Http} from 'Angular2/http';
import "rxjs/add/operator/map"
import { Injectable } from 'angular2/core';
@Injectable()
export class PostsService
{
    constructor(private _http: Http) {
    }
    getPosts()
    {
       return this._http.get("http://jsonplaceholder.typicode.com/posts")
            .map(res => res.json());
    }}

在组件内部使用服务后,我在chrome中遇到错误: 无法加载资源:服务器响应状态为404(未找到)。 chrome error details.

按以下方式调用服务的组件:

import {Component} from 'angular2/core';
import {PostsService} from '../services/posts.service'
import {HTTP_PROVIDERS} from 'angular2/http';


@Component({
    selector: 'post-list',
    template:
    `


`,
    providers: [PostsService, HTTP_PROVIDERS]

})
export class PostsComponent
{
    constructor( private _postsService: PostsService)
    {
        this._postsService.getPosts().subscribe(posts => console.log(posts));
    }
}

请注意,在index.html中导入的所有js如下:

<section id="content">
    <div class="container">
        <div class="row">
            <my-app>
                <div class="alert alert-info" role="alert">
                    <h3>Loading...</h3>
                </div>
            </my-app>
        </div>
    </div>
</section>

@section Scripts {
    <script>
        System.config({
            packages: {
                'app': { defaultExtension: 'js' },
                'lib': { defaultExtension: 'js' },
            },
        });

        System.import('app/boot')
            .then(null, console.error.bind(console));
    </script>


}

1 个答案:

答案 0 :(得分:1)

使用Angular2 beta版本,您需要在主HTML文件中包含http.js文件:

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

对于RC版本,事情发生了变化,因为现在您需要使用SystemJS配置配置Angular2模块(包括HTTP模块)