【问题标题】:Angular2 : Error during evaluation of clickAngular2:点击评估期间出错
【发布时间】:2016-02-10 13:13:25
【问题描述】:

我通过一个按钮从客户端向我使用 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');
})

【问题讨论】:

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


    【解决方案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'});
    });
    

    【讨论】:

    • 可能是因为您的服务器未在端口 3000 上运行。这与 Angular 2 无关,如果您遇到此错误,您的原始问题应该得到解决。
    • 您的服务器没有返回任何内容,因为它只是在执行 console.log,如果您不想要 404,也许您应该返回响应?我更新了我的答案
    • @flyingHawk 你试过了吗?
    【解决方案2】:

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

    【讨论】:

    • 如果您使用 lite-server,则只能使用静态内容,所以我猜您没有 deletedata 文件...这就是“未找到”错误的原因。
    • deleteddata 是服务器文件中的请求处理程序
    • 我猜你的服务器没有在端口 3000 上启动 ;-) 只有 angular2 应用程序是...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-15
    • 2018-10-05
    • 2020-07-30
    • 1970-01-01
    • 2013-03-30
    • 1970-01-01
    • 2016-09-20
    相关资源
    最近更新 更多