javascript - Angular 2 : Error during evaluation of click

标签 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:

文件结构是,有两个文件夹 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');
})

最佳答案

您可能忘记在组件中注入(inject) 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]);

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

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

关于javascript - Angular 2 : Error during evaluation of click,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35316270/

相关文章:

javascript - QBO3 无法缓存错误

json - 在 AngularJS 中读取本地文件

angularjs - Protractor angularJS 全局变量

AngularJS - 计算繁重的任务

css - 如何在将元素添加到页面时运行 CSS 动画?

javascript - 如何将推送通知从 angular 6 项目发送到 android 应用程序

angular - 为单个路由渲染多个组件?

javascript - ReactJS - 类型错误 : Cannot set property 'propOne' of undefined

javascript - CellTemplate ui-grid 中的 ng-if

javascript - 使用ip地址访问服务器时sharepoint media webpart无法播放