简体   繁体   English

Angular2 Http Post无法执行

[英]Angular2 Http Post not execute

this is my method that I call from my service it not executed 这是我从服务中调用的未执行的方法

addData(data) {
    let _body = JSON.stringify(data);
    let headers = new Headers({'Content-Type': 'application/json;charset=utf-8'});

    let url = 'http://localhost:8080/obj/addData';
    let requestoptions:RequestOptions = new RequestOptions({
         method: RequestMethod.Post,
         url: url,
         headers: headers,
         body : _body
    });
    console.log("test");
    return this._http.request(new Request(requestoptions))
        .map((res:Response) => {
            console.log(res);
            return res.json();
        });
}

I added the console.log to verify that the method is called because although I call a method nothing done 我添加了console.log来验证是否调用了该方法,因为尽管我调用了一个方法却没有做任何事情

In angular2 http requests aren't made until you subscribe to the http call. 在angular2中,只有订阅了http调用,才会发出http请求。 So if you add a subscribe to where you call the method on your service like so: 因此,如果您在服务的调用方法中添加一个订阅,如下所示:

// In some component or service using your service
this.service.addData(data).subscribe(resp => console.log(resp));

Then you should see a request made and the response data posted in the console in this case. 然后,在这种情况下,您应该看到发出的请求并将响应数据发布在控制台中。

Because the request method doesn't get executed alone. 因为request方法不会单独执行。 Given you're already subscribing to the addData method, I'd suggest using the post method instead like this: 鉴于您已经订阅了addData方法,建议您使用post方法,如下所示:

addData(data) {
    let _body = JSON.stringify(data);
    let headers = new Headers({'Content-Type': 'application/json;charset=utf-8'});

    let url = 'http://localhost:8080/obj/addData';

    console.log("test");

    return this._http.post(url, _body, { headers })
        .map((res:Response) => {
            console.log(res);
            return res.json();
        });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM