Javascript 角度2:单击评估期间出错
我通过一个按钮从客户端向服务器发出请求,这个按钮是我使用express创建的,在请求处理程序中只有console.log(“从服务器删除”); 每次我点击它,我都会发现这些错误Javascript 角度2:单击评估期间出错,javascript,angularjs,angular,angular2-routing,angular2-directives,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 e
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');
})
我认为您忘记将
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 ]);
在引导主组件时,不要忘记添加相应的提供程序:
@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()); })
}
}
不要忘记在引导程序中添加HTTP\u提供程序
:
bootstrap(MyComponent, [HTTP_PROVIDERS]);
您的服务器还应返回以下内容:
server.get('/deletedata', function(req, res) {
res.json({hello: 'hello world'});
});
可能是因为服务器未在端口3000上运行。这与Angular 2无关,如果出现此错误,您的原始问题应该得到解决。您的服务器没有返回任何内容,因为它只是在执行console.log,如果您不想要404,您可能应该返回响应?我更新了我的answer@flyingHawk你试过了吗?如果你使用lite服务器,你只能使用静态内容,所以我猜你没有
deletedata
文件。。。这就是“找不到”错误的原因。deletedata是服务器文件中的请求处理程序我猜您的服务器没有在端口3000上启动;-)只有angular2应用程序是。。。