【问题标题】:Symfony 4 / angular 8 : read nested JSON and fill object with its contentSymfony 4 / angular 8:读取嵌套 JSON 并用其内容填充对象
【发布时间】:2019-09-03 09:30:36
【问题描述】:

我正在尝试从 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 服务器错误(内部服务器错误):

错误:“数组[城市]:↵此字段丢失。(代码 2fa2158c-2a7f-484b-98aa-975522539ff8)↵数组[国家]:↵此字段 不见了。 (代码 2fa2158c-2a7f-484b-98aa-975522539ff8)↵Array[street]:↵ 这个字段是 失踪。 (代码 2fa2158c-2a7f-484b-98aa-975522539ff8)↵数组[邮编]:↵这个 字段丢失。 (代码 2fa2158c-2a7f-484b-98aa-975522539ff8)↵数组[地址]:↵这个字段 没想到。 (代码 7703c766-b5d5-4cef-ace7-ae0dd82304e9)↵"

一些帮助!

【问题讨论】:

    标签: json angular symfony request response


    【解决方案1】:

    我假设,由于您发送的对象包含地址作为子结构,您的 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"),
            )),
        ));
    

    【讨论】:

      猜你喜欢
      • 2020-09-14
      • 1970-01-01
      • 2017-10-03
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-16
      • 1970-01-01
      相关资源
      最近更新 更多