Angular2:评估点击时出错

时间:2016-02-10 13:13:25

标签: javascript angularjs angular angular2-routing angular2-directives

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

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:

文件结构是,有两个文件夹服务器和客户端分别有角度和服务器文件

这是按钮点击功能:

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

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

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

2 个答案:

答案 0 :(得分:1)

我认为您忘记将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 ]);

答案 1 :(得分:1)

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

你应该有类似的东西:

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

  constructor(private http: Http) { }

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

}

不要忘记在引导程序中添加HTTP_PROVIDERS

bootstrap(MyComponent, [HTTP_PROVIDERS]);

您的服务器也应该返回一些内容:

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