Angular2:点击评估期间出错

Angular2 : Error during evaluation of click

我通过使用 express 创建的从客户端到服务器的按钮发出请求,在请求处理程序中只有 console.log('Delete from server'); 每次我点击它都会收到这些错误

angular2.dev.js:23514 ORIGINAL EXCEPTION: T
ypeError: Cannot read property    'request' of undefined
angular2-polyfills.js:143 Uncaught EXCEPTION:
Error during evaluation of   "click"
ORIGINAL EXCEPTION: TypeError: Cannot read property 'request' of undefined
ORIGINAL STACKTRACE:

文件结构是,有两个文件夹server和client分别有angular和server文件

点击按钮的函数如下:

 deletefromserver(){
     this.http.request("http://localhost:3000/deletedata").subscribe((res :     Response) => {
        console.log(res.json());
    })     
 }

这是服务器文件中的请求处理程序:

server.get('/deletedata', function(){
console.log('Delete from server');
})

我认为您忘记将 Http 实例注入到您的组件中:

@Component({
  (...)
})
export class MyComponent {
  constructor(private http:Http) {
  }
}

在启动主要组件时不要忘记添加相应的提供程序:

import {bootstrap} from 'angular2/platform/browser';
import {HTTP_PROVIDERS} from 'angular2/http';
import {AppComponent} from './app.component';

bootstrap(AppComponent, [ HTTP_PROVIDERS ]);

您可能忘记在您的组件中注入 http 服务

你应该有这样的东西:

@Component({...})
class MyComponent {

  constructor(private http: Http) { }

  deleteFromServer() {
    this.http.request("http://localhost:3000/deletedata").subscribe((res : Response) => { console.log(res.json()); })
  }

}

并且不要忘记在 bootstrap 中添加 HTTP_PROVIDERS:

bootstrap(MyComponent, [HTTP_PROVIDERS]);

您的服务器还应该 return 东西:

server.get('/deletedata', function(req, res) {
  res.json({hello: 'hello world'});
});