【问题标题】:Not able to send Object to rest API in angular 6无法以角度 6 将对象发送到休息 API
【发布时间】:2019-04-16 09:07:20
【问题描述】:

我正在使用 Rest API 并希望保存用户数据,我能够访问 API 但无法发送对象。它在 API 中显示为 null。

我检查了我的控制台和网络,它显示的是 Angular 应用程序 URL 而不是 API URL。

export class UserService {
  url = 'http://localhost:8085/api/employees';
  constructor(private http: HttpClient) {}

  userData(user: User): Observable<any> {
    const params = new HttpParams().set('id', '5').
    set('userName', 'Bisnu').set('salary', '100').set('department', 'IT').set('password', 'mohan')
    .set('firstName', 'Bisnu').set('lastName', 'Biswal');
    const newUser = {
      userName: 'Bisnu',
      salary: 100,
      password: 'mohan',
      department: 'IT',
      firstName: 'Bisnu',
      lastName: 'Mohan'
    };

    console.log(newUser);
    console.log(this.url);
    return this.http.post<any>(this.url, newUser);
  }
}

我从组件调用这个服务

onSubmit(){
    console.log(this.user);
    this.userService.userData(this.user).subscribe(
      data => console.log("success", data),
      error => console.error("Error!",error)
    );
    this.resetForm();
  }
}

我检查的浏览器控制台如下,这是错误的。

控制器如下

用户模型如下

【问题讨论】:

  • 你能打API调用吗?
  • yes Shahid,能够访问 API,但值显示为 null,无法识别问题所在。我硬编码了这些值,但仍然是空值。我给出的屏幕截图,在那个请求 URL 中显示错误,方法也显示“GET”,但我已经发布了。
  • 如果您能够使用空值访问 API,那么您向我们展示的屏幕截图必须是不同的请求。如果您的 API 被命中,则必须向它发出请求。在出现空值的地方显示 API 中的代码可能很有用。
  • 这是一个简单的REST API
  • 我遇到过这种问题。请使用后端验证您的数据类型。如果您从角度侧发送浮点值或字符串值,并且在 api 侧数据类型为 int,那么您将获得空值。请在您的代码中验证您的数据类型,我可以看到,在一个地方薪水是字符串,第二个地方您将值发送为 int

标签: java angular spring typescript


【解决方案1】:

试试这个,后端对象和你的 newuser 对象不匹配。

    userData(user: User): Observable<any> {
          user.Id :1;
          user.userName: 'Bisnu';
          user.salary: 100;
          user.password: 'mohan';
          user.department: 'IT';
          user.firstName: 'Bisnu';
          user.lastName: 'Mohan';

        return this.http.post<any>(this.url, user);
      }

【讨论】:

  • 你能解释一下这个答案吗?
  • 这不是有效的 javascript。此外,您的解释没有意义,当您没有看到后端对象时,后端对象和newuser 对象如何不匹配,因为它尚未由 OP 发布?此外,即使您的代码是有效的,它与 OP 最初发布的代码也没有区别,除了如果将空 user 作为参数传递,您的代码会爆炸。
  • @UncleDave 检查 UserModel,他没有传递“Id”参数
  • @BhargilJoshi 现在可以访问 API,userData(user: User): Observable { user.Id = 10; user.UserName = 'Bisnu'; user.Salary = '100'; user.Password = 'mohan'; user.Department = 'IT'; user.FirstName = 'Bisnu'; user.LastName = '莫汉';控制台.log(用户);返回 this.http.post(this.url,user);
  • 我可以看到请求有效负载中的值,但在 API 中这些值显示为空,我需要做任何转换还是什么?
猜你喜欢
  • 1970-01-01
  • 2018-12-28
  • 2019-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-07
  • 2019-03-01
  • 2019-07-19
相关资源
最近更新 更多