【问题标题】:unable to send data from angular 2 front end to backend rest api无法将数据从 Angular 2 前端发送到后端 rest api
【发布时间】:2018-01-05 04:27:39
【问题描述】:

如何从后端调用rest api发送数据并获取json对象中的用户数据

 import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { User } from '../_models/index';

import { Http, Response, Headers, RequestOptions } from '@angular/http';


@Injectable()
export class UserService {
constructor(private http: HttpClient) { }



create(user: User) {
    console.log("in create user");
 return this._http.get("http:// localhost:8082/register").map(res => 
res.json());
//    return this.http.post('/api/users', user);
}
}

以上是 angular2 service.ts 代码发送用户数据休息

下面是RegisterComponent component.ts代码:

import { Component } from '@angular/core';
import { Router } from '@angular/router';

import { AlertService, UserService } from '../_services/index';

@Component({
moduleId: module.id.toString(),
templateUrl: 'register.component.html'
})

export class RegisterComponent {
model: any = {};
loading = false;

constructor(
    private router: Router,
    private userService: UserService,
    private alertService: AlertService) { }

register() {
    this.loading = true;
    this.userService.create(this.model)
        .subscribe(
            data => {
                this.alertService.success('Registration successful', true);
                this.router.navigate(['/login']);
            },
            error => {
                this.alertService.error(error);
                this.loading = false;
            });
}

}

从上面的组件创建正在调用服务方法创建,我想在后端 api 中调用 post 方法

下面是rest api

@RequestMapping(value = "/register", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE,
        MediaType.APPLICATION_XML_VALUE })
public ResponseEntity<Void> registrationUser(@RequestBody UserDetails user, HttpServletRequest request,
        HttpSession session, HttpServletResponse response) {
    if (user.getEmail() != null && user.getName() != null && user.getPhoneNumber() != null
            && user.getPassword() != null) {
        String name = user.getName();
        String email = user.getEmail();
        String phoneNumber = user.getPhoneNumber();
        String password = user.getPassword();
        {....
       }

                SendMail.sendMail(to, subject, msg);
                System.out.println("mail send");
                return new ResponseEntity<Void>(HttpStatus.OK);
            }
            return new ResponseEntity<Void>(HttpStatus.CONFLICT);

        } else
            return new ResponseEntity<Void>(HttpStatus.CONFLICT);
    }
    return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}

错误: src/app/_services/user.service.ts(6,57) 中的错误:错误 TS2307:找不到模块“@angular/http”。 src/app/_services/user.service.ts(28,14):错误 TS2551:“UserService”类型上不存在属性“_http”。你是说“http”吗?

【问题讨论】:

  • 错误正确地提及“UserService”类型上不存在属性“_http”因为您在构造函数中注入了 http 而不是 _http。你有没有检查纠正它。
  • 检查浏览器的控制台是否有任何Access-Control-Allow-Origin 错误?
  • 签入spring,您已经为/register 编写了POST 方法/register", method = RequestMethod.POST,并且从角度您正在为/register API 调用get 方法this.http.get
  • 感谢您的努力,我能够在后端休息中发送数据:错误出现在 :: import { Injectable } from '@angular/core';从“@angular/common/http”导入 { HttpClient };从'../_models/index'导入{用户}; //从'@angular/http'导入{Http,Response};从'rxjs'导入{ Observable };导入'rxjs/add/operator/map';导入'rxjs/add/operator/toPromise';
  • register() { this.loading = true; this.userService.create(this.model) .subscribe( data => { this.alertService.success('注册成功', true); this.router.navigate(['/login']); }, error => { this.alertService.error(error); this.loading = false; }); }

标签: angular rest api


【解决方案1】:

此代码 sn-p 来自您的第一个代码块中的代码。

return this._http.get("http:// localhost:8082/register").map(res => res.json());

我相信您希望阅读此行

return this.http.get("http:// localhost:8082/register").map(res => res.json());

这似乎是错误所抱怨的。祝你好运!

【讨论】:

  • 是的错误在那一行,但问题是我无法从后端的 api 发送/获取数据
  • 我从 ::jasonwatmore.com/post/2016/08/16/… 引用了这段代码,并希望将调用发送到 rest api
  • 没有更多细节,我不确定您现在遇到的错误是什么。我真正必须继续的唯一上下文是有一个错字。也许包括你得到的新错误是什么。
【解决方案2】:

第一个错误

错误:src/app/_services/user.service.ts(6,57) 中的错误:错误 TS2307:找不到模块 '@angular/http

在 app.module.ts 中添加 HttpModule

 import {HttpModule} from '@angular/http'

 @NgModule({
    imports:[
      HttpModule
    ]
 })

第二个错误

错误 TS2551:“UserService”类型上不存在属性“_http”。你是说“http”吗?

你的代码看起来不对

constructor(private http: HttpClient) { }

声明的变量名http。但是你用像_http

 return this._http.get("http:// localhost:8082/register").map(res => 

所以改变这一行 this.http 而不是 this._http

 return this.http.get("http:// localhost:8082/register").map(res => 

希望这能解决您的错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    • 2018-11-28
    • 2019-01-25
    • 1970-01-01
    相关资源
    最近更新 更多