Symfony 4 / angular 8:读取嵌套的 JSON 并用其内容填充对象

Symfony 4 / angular 8 : read nested JSON and fill object with its content

我正在尝试从 angular 端向 symfony 服务器发送一个 post http 请求以注册用户,我的用户对象包含第二个对象,即地址 json对象看起来像这样:

{
  "user": {
    "firstname": "b",
    "last name": "d",
    "email": "f",
    "password": "f",
    "civility": "f",
    "phone": "f",
    "Address": {
      "city":"rr",
      "country":"rr",
      "postalcode":"77"
    }

  }
}

我正在通过我的服务在前端发送请求:

export class RegisterService {
  user: User;
  address: Address;
  constructor(private http: HttpClient) { }

  registerUser(civility: string, firstname: string, lastname: string, tel: string, street: string, city: string, country: string, postalcode: number, email: string, password: string, ): Promise<any> {
    this.user = new User();
    this.address = new Address()

    this.user.username = email;
    this.user.civility = civility;
    this.user.firstname = firstname;
    this.user.lastname = lastname;
    this.user.tel = tel;
    this.user.email = email;
    this.user.password = password;

    this.address.street = street;
    this.address.city = city;
    this.address.country = country;
    this.address.postalcode = postalcode;

    this.user.address = this.address;
    console.log(this.user);
    return this.http.post((`${config.apiUrl}/api/auth/register`), this.user).toPromise();
  }
}

这是我在 symfony 部分所做的工作:

/**
     * @Route("/register", name="api_auth_register",  methods={"POST"})
     * @param Request $request
     * @param UserManagerInterface $userManager
     * @return JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function register(Request $request, UserManagerInterface $userManager)
    {
        $data = json_decode(
            $request->getContent(),
            true
        );
        $validator = Validation::createValidator();
        $constraint = new Assert\Collection(array(
            'username' => new Assert\Type("string"),
            'password' => new Assert\Length(array('min' => 6)),
            'email' => new Assert\Email(),
            'firstname' => new Assert\Type("string"),
            'lastname' => new Assert\Type("string"),
            'tel' => new Assert\Type("string"),
            'civility' => new Assert\Type("string"),
            'city' => new Assert\Type("string"),
            'country' => new Assert\Type("string"),
            'street' => new Assert\Type("string"),
            'postalcode' => new Assert\Type("string"),

        ));
        $violations = $validator->validate($data, $constraint);
        if ($violations->count() > 0) {
            return new JsonResponse(["error" => (string) $violations], 500);
        }

        $user = new User();
        $address = new Adress();


        var_dump($data);

        $user->setPlainPassword($data['password']);
        $user->setEmail($data['email']);
        $user->setEnabled(true);
        $user->setRoles(['ROLE_USER']);
        $user->setSuperAdmin(false);
        $user->setLastname($request->get('lastname'));
        $user->setFirstname($request->get('firstname'));
        $user->setTel($request->get('tel'));
        $user->setCivility($request->get('civility'));


        $address->setCity($request->get('city'));
        $address->setCountry($request->get('country'));
        $address->setStreet($request->get('street'));
        $address->setPostalCode($request->get('postalcode'));
        $user->setAddress($address);
        $em = $this->getDoctrine()->getManager();
        $em->persist($address);
        $em->flush();

        try {
            $userManager->updateUser($user, true);
        } catch (\Exception $e) {
            return new JsonResponse(["error" => $e->getMessage()], 500);
        }
        return new JsonResponse(["success" . " has been registered!"], 200);

我收到 500 服务器错误(内部服务器错误),即:

error: "Array[city]:↵ This field is missing. (code 2fa2158c-2a7f-484b-98aa-975522539ff8)↵Array[country]:↵ This field is missing. (code 2fa2158c-2a7f-484b-98aa-975522539ff8)↵Array[street]:↵ This field is missing. (code 2fa2158c-2a7f-484b-98aa-975522539ff8)↵Array[postalcode]:↵ This field is missing. (code 2fa2158c-2a7f-484b-98aa-975522539ff8)↵Array[address]:↵ This field was not expected. (code 7703c766-b5d5-4cef-ace7-ae0dd82304e9)↵"

一些帮助!

我假设,由于您发送的对象包含作为子结构的地址,因此您的 Assert\Collection 应该有一个 address 键,以模仿预期的格式:

    $constraint = new Assert\Collection(array(
        'username' => new Assert\Type("string"),
        'password' => new Assert\Length(array('min' => 6)),
        'email' => new Assert\Email(),
        'firstname' => new Assert\Type("string"),
        'lastname' => new Assert\Type("string"),
        'tel' => new Assert\Type("string"),
        'civility' => new Assert\Type("string"),
        'address' => new Assert\Collection(array(
          'city' => new Assert\Type("string"),
          'country' => new Assert\Type("string"),
          'street' => new Assert\Type("string"),
          'postalcode' => new Assert\Type("string"),
        )),
    ));