GVKun编程网logo

从Struts中的angular 2发送和接收htttp post数据(angular发送http请求)

18

以上就是给各位分享从Struts中的angular2发送和接收htttppost数据,其中也会对angular发送http请求进行解释,同时本文还将给你拓展$http.post在AngularJS中不

以上就是给各位分享从Struts中的angular 2发送和接收htttp post数据,其中也会对angular发送http请求进行解释,同时本文还将给你拓展$ http.post在AngularJS中不起作用、Angular 2 http.post () 没有发送请求 - Angular 2 http.post () is not sending the request、Angular 2 http.post() 没有发送请求、Angular 4.3 HttpClient (Angular访问 REST Web 服务) 二、Http POST等相关知识,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

从Struts中的angular 2发送和接收htttp post数据(angular发送http请求)

从Struts中的angular 2发送和接收htttp post数据(angular发送http请求)

我正在尝试将来自角度4代码的http发布数据发送到struts动作。正在调用Struts操作,但无法接收数据。给我一个错误,例如“
java.lang.ClassCastException:java.lang.Integer无法转换为java.lang.String”

建议将有很大帮助

    import { Component, OnInit } from ''@angular/core'';import { Http, Headers, RequestOptions } from ''@angular/http'';import ''rxjs/add/operator/toPromise'';import { Observable } from ''rxjs/Observable'';@Component({  selector: ''app-root'',  template: ''<h1>Dukes</h1>'',  // templateUrl: ''./app.component.html'',  styleUrls: [''./app.component.css'']})export class AppComponent implements OnInit {  title = ''here beta'';  dukes = [{ name: "offline", age: 2 }];  data = {    title: ''foo'',    body: ''bar'',    userId: 1  };  headers: Headers = new Headers({ ''Content-Type'': ''application/json'' });  options: RequestOptions = new RequestOptions({ headers: this.headers });  constructor(private http: Http) { }  ngOnInit() {    let options = new RequestOptions();    options.headers = new Headers();    options.headers.append(''Content-Type'', ''application/json'');    const req = this.http.post(''http://localhost:8080/SampleProject/getTutorial'', this.data, options)      .subscribe(      res => {        console.log(res);      },      err => {        console.log("Error occured");      }      );

支柱行动课是

    public class SampleAction {   private String data; public String getData() {            return data;        }        public void setData(String data) {            this.data = data;        }    public int execute()     {          try{         actorSeqID = 3;         System.out.println(data+"--");        }catch(Exception e){            e.printStackTrace();        }      return "success";     }

答案1

小编典典

如果要以data字符串形式获取,则应尝试如下操作:

    import { Component, OnInit } from ''@angular/core'';import { Http, Headers, RequestOptions } from ''@angular/http'';import ''rxjs/add/operator/toPromise'';import { Observable } from ''rxjs/Observable'';@Component({  selector: ''app-root'',  template: ''<h1>Dukes</h1>'',  // templateUrl: ''./app.component.html'',  styleUrls: [''./app.component.css'']})export class AppComponent implements OnInit {  title = ''here beta'';  dukes = [{ name: "offline", age: 2 }];      data = "data=\"{title: ''foo'',body: ''bar'',userId: 1};\"";  headers: Headers = new Headers({ ''Content-Type'': ''application/x-www-form-urlencoded'' });  options: RequestOptions = new RequestOptions({ headers: this.headers });  constructor(private http: Http) { }  ngOnInit() {    let options = new RequestOptions();    options.headers = new Headers();    options.headers.append(''Content-Type'', ''application/x-www-form-urlencoded'');    const req = this.http.post(''http://localhost:8080/SampleProject/getTutorial'', this.data, options)      .subscribe(      res => {        console.log(res);      },      err => {        console.log("Error occured");      }      );

但我认为您想通过json将它们全部设置为不同的动作属性,如果是,请定义的setter
titlebody然后userId在您的动作中继续使用Struts JSON插件-
JSON拦截器

另一个例子

import { Component, OnInit } from ''@angular/core'';import { Http, Headers, RequestOptions } from ''@angular/http'';import ''rxjs/add/operator/toPromise'';import { Observable } from ''rxjs/Observable'';@Component({  selector: ''app-root'',  template: ''<h1>Dukes</h1>'',  // templateUrl: ''./app.component.html'',  styleUrls: [''./app.component.css'']})export class AppComponent implements OnInit {  title = ''here beta'';  dukes = [{ name: "offline", age: 2 }];  data = {    "title": "foo",    "body": "bar",    "userId": 1  };  headers: Headers = new Headers({ ''Content-Type'': ''application/json'' });  options: RequestOptions = new RequestOptions({ headers: this.headers });  constructor(private http: Http) { }  ngOnInit() {    let options = new RequestOptions();    options.headers = new Headers();    options.headers.append(''Content-Type'', ''application/json'');    const req = this.http.post(''http://localhost:8080/SampleProject/getTutorial'', JSON.stringify(this.data)/*CONVERTS DATA TO STRING*/, options)      .subscribe(      res => {        console.log(res);      },      err => {        console.log("Error occured");      }      );

    public class SampleAction {   private String title; public String getTitle() {            return title;        }        public void setTitle(String title) {            this.title = title;        }   private String body; public String getBody() {            return body;        }        public void setBody(String body) {            this.body= body;        }   private int userId; public String getUserId() {            return userId;        }        public void setUserId(int userId) {            this.userId= userId;        }    public int execute()     {          try{         actorSeqID = 3;         System.out.println(data+"--");        }catch(Exception e){            e.printStackTrace();        }      return actorSeqID;     }

<package name="default" namespace="/" extends="struts-default,json-default">        <action name="getTutorial" method="execute">            <interceptor-ref name="json"></interceptor-ref>        </action></package>

$ http.post在AngularJS中不起作用

$ http.post在AngularJS中不起作用

当我使用$http.get我的代码时,但是如果我使用$ http.post,则永远不会将参数获取到请求.php文件中。

这是服务功能:

    TestPanel.service('MySampleService',function ($http,$q) {
    this.getAllPosts = function () {

        var def = $q.defer();
        $http.post('/data/AJAXRequest.php','mydata=1&abcd=2').success(function (data) {
            if (data == null)
                def.reject('ERROR: DATA IS NULL');
            else if (data.HasError)
                def.reject('ERROR: ' + data.Message);
            else
                def.resolve(data);
        }).error(function () {
            def.reject('ERROR: Sorry,unable to complete your request.');
        });

        return def.promise;
    }
});

和控制器功能:

 TestController.controller('PostCtrl',['$scope','$http','MySampleService',function ($scope,$http,MySampleService) {

        function FetchPostsList() {
            MySampleService.getAllPosts().then(function (data) {
                $scope.lstPosts = data.ResponseData;
                $scope.totalRecords = data.totalRecords;
                console.info('DATA=' + $scope.lstPosts);
            },function (err) {
                console.info('err=' + err);
            });
        }

        FetchPostsList();
    }
]);

和我的AJAXRequest.php文件

<?php 
   var_dump($_POST)
?>

如果我使用 $ http.post()

输出

 array (size=0)
  empty

如果我使用 $ http.get(), 我的输出是:

array (size=2)
  'mydata' => string '1' (length=1)
  'abcd' => string '2' (length=1)

我检查了FireBug工具中的帖子,该帖子将数据发送到我的php文件中。但PHP文件没有参数。

如果我使用 $ .ajax$ .post 我的代码工作,它会给出响应。

Angular 2 http.post () 没有发送请求 - Angular 2 http.post () is not sending the request

Angular 2 http.post () 没有发送请求 - Angular 2 http.post () is not sending the request

问题:

When I make a post request the angular 2 http is not sending this request 当我发出帖子请求时,angular 2 http 没有发送此请求

this.http.post(this.adminUsersControllerRoute, JSON.stringify(user), this.getRequestOptions())

the http post is not sent to the server but if I make the request like this http post 不会发送到服务器,但如果我发出这样的请求

this.http.post(this.adminUsersControllerRoute, JSON.stringify(user), this.getRequestOptions()).subscribe(r=>{});

Is this intended and if it is can someone explain me why ? 这是有意的,如果是的话,有人可以解释我为什么吗? Or it is a bug ? 或者它是一个错误?


解决方案:

参考: https://stackoom.com/en/question/2RvXo

Angular 2 http.post() 没有发送请求

Angular 2 http.post() 没有发送请求

当我发出 post 请求时,angular 2 http 未发送此请求

this.http.post(this.adminUsersControllerRoute, JSON.stringify(user), this.getRequestOptions())

http post 不会发送到服务器,但如果我发出这样的请求

this.http.post(this.adminUsersControllerRoute, JSON.stringify(user), this.getRequestOptions()).subscribe(r=>{});

这是有意的吗?如果有人可以解释我为什么?或者它是一个错误?

答案1

小编典典

由于该类的post方法Http返回一个可观察对象,因此您需要订阅它以执行其初始化处理。Observables 是惰性的。

您应该观看此视频以了解更多详细信息:

  • https://egghead.io/lessons/rxjs-rxjs-observables-vs-promises

Angular 4.3 HttpClient (Angular访问 REST Web 服务) 二、Http POST

Angular 4.3 HttpClient (Angular访问 REST Web 服务) 二、Http POST

用HttpClient发送数据

发送数据使用HttpClient post方法。
发送POST必须要有一个支持a REST API POST http请求的后台支持。
POST方法:

const req = this.http.post('http://jsonplaceholder.typicode.com/posts',{
      title: 'foo',body: 'bar',userId: 1
    })
      .subscribe(
        res => {
          console.log(res);
        },err => {
          console.log("Error occured");
        }
      );

关于从Struts中的angular 2发送和接收htttp post数据angular发送http请求的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于$ http.post在AngularJS中不起作用、Angular 2 http.post () 没有发送请求 - Angular 2 http.post () is not sending the request、Angular 2 http.post() 没有发送请求、Angular 4.3 HttpClient (Angular访问 REST Web 服务) 二、Http POST的相关信息,请在本站寻找。

本文标签: