404获取angular2 / http - 请求到api

时间:2016-04-28 09:59:19

标签: angular

我又回来了另一个问题.. 我的本地服务器上有一个API,我想与它通信。 但是当我做的时候

import {Http, Response} from 'angular2/http'; or  
import { HTTP_PROVIDERS } from 'angular2/http'; or  
import {HTTP_BINDINGS} from 'angular2/http'; or  
import {Http, Response} from 'angular2/http';

我收到了错误消息?控制台中的“404 GET / angular2 / http”。

这是我的toolservice.ts:

 import {Injectable} from 'angular2/core';  
 import {Http, Response} from 'angular2/http';  
 import {Tool} from './tool';  
 import {BackendService} from './backend.service';  

 @Injectable()  
 export class ToolService {  
 constructor(  
     private _backend: BackendService /*,http: Http*/ ){ }  

   private _tools:Tool[] = [];  

   getTools() {  
     this._backend.getAll(Tool).then( (tools:Tool[]) => {  
       this._tools.push(...tools); // fill cache  
     });
     return this._tools;   }  
     /*launchtool(){  
     alert("I asked to launch your tool...");  
     http.get("http://localhost:8080/");  
     //this.http.get("http://localhost:8080/");  
    //$http.get("http://localhost:8080/");  
    }*/  
 }

如果我取消注释“private _backend:BackendService / ,私有http:Http /){}” 我得到一个错误导致angular无法找到http。

我错过了什么吗?我尝试做npm install -g http和http-request但是它无效..

1 个答案:

答案 0 :(得分:0)

这是一项服务。

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

@Injectable()
export class BackendService {
    constructor(private _http: Http) {}
getAll():Observable<any> {
return this._http.get('http://localhost:8080/')
.map(res => res.json());
};

这是组件

import { BackendService } from './backend.service';
constructor(private backendservice: BackendService) { }
data: any[];

get(): void {
this.backendservice.getAll().subscribe(data => this.data = data,
error => console.log(error));
}