Http故障响应

时间:2019-04-29 14:47:00

标签: angular symfony

我正在与Symfony和angular一起实现一个小型项目。我在我的routing.yml文件中添加了一条路由来编辑用户。在有角度的前端中,我尝试通过其ID检索用户,但出现404错误。

No route found for "GET /user/NaN" (from "http://localhost:4200/edit-user")

这是routing.yml文件:

pr_manager_update:
    path:     /user/update/{id}
    defaults: { _controller: PrManagerBundle:User:update}

角度服务:

getUserById(id: number) {
  return this.http.get(Statique.USER_ID + '/' + id);
 }
static USER_ID = 'http://localhost/project-manager/backend/web/app_dev.php/user';

以及组件:

import { Component, OnInit } from '@angular/core';
import { eb_user } from 'src/app/classes/eb_user';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { CreateService } from 'src/app/services/create.service';
import { first } from 'rxjs/operators';

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.scss']
})
export class EditComponent implements OnInit {

  user: eb_user[];
  updateForm: FormGroup;

  constructor(private formBuilder: FormBuilder,
              private router: Router,
              private createService: CreateService) { }

  ngOnInit() {
    let userId = localStorage.getItem("editUserId");
    if(!userId){
      alert("erreur")
      this.router.navigate(['liste-user']);
      return;
    }
    this.updateForm = this.formBuilder.group({
      id: [],
      nom: ['', Validators.required],
      prenom: ['', Validators.required],
      tel: ['', Validators.required],
      mail: ['', Validators.required],
      domaine: ['', Validators.required],
      //client: eb_user[];
      //x_eb_role : ['', Validators.required],
    });
    this.createService.getUserById(+userId)
        .subscribe(data => {this.updateForm.setValue(data);});
  }

  onSubmit(){
    this.createService.editUser(this.updateForm.value)
        .pipe(first())
        .subscribe(
          data =>{
            this.router.navigate(['liste-user']);
          },
         error => {
           alert(error);
         }

        );
  }

}

我希望后端和前端之间的连接正确完成

1 个答案:

答案 0 :(得分:1)

您的userId可能不是数字,请参见以下示例:

let userId = "10"; // a numberic string
console.log(+userId); // will give a number 10

userId = "hello"; // a non numeric string
console.log(+userId); // will give NaN

URL仍然是字符串,您不需要将userId解析为数字,该数字最终将再次与字符串连接,只需执行以下操作:

this.createService.getUserById(userId) // no +userId
        .subscribe(data => {this.updateForm.setValue(data);})

修改方法getUserById()的参数类型:

getUserById(id: string | number) {
  return this.http.get(Statique.USER_ID + '/' + id);
}