首页 文章

发布请求未发送到服务器

提问于
浏览
0

我正在尝试将数据发布到我从表单中提取的API中 .

问题是它根本不会尝试发送帖子请求 . Register.component.ts:

import { Component, OnInit } from '@angular/core';
import { RegisterService } from '../register.service';
import { FormGroup, FormBuilder, FormControl, Validators, FormArray, ReactiveFormsModule } from '@angular/forms';
import { user } from '../user'
@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
  public myForm: FormGroup;
  public submitted: boolean;
  public events: any[] = [];

  constructor(private registerService: RegisterService, 
  private _fb: FormBuilder) { }

  ngOnInit() {
    this.myForm = new FormGroup({
      username: new FormControl('', [<any>Validators.required, <any>Validators.minLength(5)]),
      email: new FormControl('', [<any>Validators.required, <any>Validators.minLength(5)]),
      org_number: new FormControl('', [<any>Validators.required, <any>Validators.minLength(5)]),
      password: new FormControl('', [<any>Validators.required, <any>Validators.minLength(8)])
    });
  }

  save(model: user, isValid: boolean){
    this.submitted = true;
    this.registerService.postUser(model)
    console.log(model, isValid)
  }

它正在呼叫的服务:

import { Injectable } from '@angular/core';
import { user } from './user';
import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators'
import { HttpClient, HttpHeaders } from '@angular/common/http';

const HttpOptions = {
  headers: new HttpHeaders({ 'Content-type': 'application/json' })
};
const HttpOption2 = {
  headers: new HttpHeaders({ 'Content-type': 'application/x-www-form-urlencoded' })
}
@Injectable({
  providedIn: 'root'
})
export class RegisterService {

  private usersUrl= 'api/v1/accounts';

  constructor(
    private http: HttpClient,

  ) { }

  getUsers(): Observable<user[]> {
    return this.http.get<user[]>(this.usersUrl)
  }
  postUser(object): Observable<user[]>{
    console.log(object)
    console.log('Did it enter this?')
    return this.http.post<user[]>(this.usersUrl, user, HttpOptions)
  }
}

我的代码输出了预期的信息:用户名:'用户名',电子邮件:'电子邮件'等 .

我知道它调用了函数,因为它也输出:'它输入了吗?' .

我的API不是't receiving a post-request and I have no idea why. I'已经在official angular Httpclient页面上搜索答案,以及众多Stack溢出帖子,我've tried adding .subscribe but I get the error type subscription is not assignable to type observable user, if i add .map() I get that map does not exist on type observable user, and if i add .pipe() I get no error message, but still no Post-request. Whereas if i add .pipe( catchError(this.handleError(' addHero',英雄)));我得到类型observable用户不能分配给observable用户类型 . 有任何想法吗?

1 回答

  • 2

    您需要订阅要调用的请求,

    this.registerService.postUser(model).subscribe(result => this.result =result);
    

    确保声明一个名为result的变量来分配响应的数据,

    result : any;
    

相关问题