PHP - проблема передачи информации между PHP, Angular и HTTP? - PullRequest
0 голосов
/ 18 сентября 2018

Я работаю над сайтом Laravel PHP и получаю сообщение об ошибке при попытке добавить пользователя в ячейку таблицы

Ошибка говорит:

Anпроизошла ошибка при добавлении вашего контакта.Если проблема не устраняется, свяжитесь с нами.

и отображается в виде красной ленты, которая на несколько секунд появляется под адресной строкой браузера при попытке выбрать нового пользователя из выпадающего списка.вниз.

Я видел пару похожих вопросов на SO, но не могу понять, как какой-либо из ответов относится к тому, что здесь происходит ...

В HTML столбец таблицы, значение ячейки которого я пытаюсь обновить, выполняется с помощью формы, которая появляется в диалоговом окне при нажатии значка «Изменить» в ячейке:

<div class="provTaxContacts__row">
    <form [formGroup]="newContactForm" class="provTaxContacts__col provTaxContacts__new-contact">
        <label>Add new contact</label>
        <div class="provTaxContacts__new-contact-fields">
            <input class="provTaxContacts__new-contact-field provTaxContacts__name" [class.error]="newContactFormErrors.contactFirstName" placeholder="First name" type="text" autocomplete="given-name" formControlName="contactFirstName" />
            <input class="provTaxContacts__new-contact-field provTaxContacts__name" [class.error]="newContactFormErrors.contactLastName" placeholder="Last name" type="text" autocomplete="family-name" formControlName="contactLastName" />
            <input class="provTaxContacts__new-contact-field provTaxContacts__email" [class.error]="newContactFormErrors.contactEmail" placeholder="Email address" type="email" autocomplete="email" formControlName="contactEmail" />
            <button class="btn btn-primary provTaxContacts__new-contact-button" type="button" (click)="onNewContactAdd(taxpayer.accountId)">Add contact</button>
            <div *ngIf="addContactLoading" class="spinner-loading"></div>
        </div>
    </form>
</div>

onNewContactAdd() функция, которая вызывается при нажатии кнопки «Добавить контакт», определена в файле Typescript под названием tax-remder.ts, а также обрабатывает то, что происходит с браузером на внешнем интерфейсе, она также вызывает функцию addUserToAccount() изuser.service.ts.Это то, что отображает ошибку в браузере, и определяется с помощью:

onNewContactAdd(accountId: number) {
    const firstName = this.newContactForm.get('contactFirstName').value;
    const lastName = this.newContactForm.get('contactLastName').value;
    const email = this.newContactForm.get('contactEmail').value;
    // Reset error states
    this.resetContactFormErrors();

    // Check for form errors
    if (!firstName || Validate.isEmpty(firstName) || !Validate.lettersAndSpaces(firstName)) {
        this.newContactFormErrors.contactFirstName = true;
    } else {
        this.newContactFormErrors.contactFirstName = false;
    }

    if (!lastName || Validate.isEmpty(lastName) || !Validate.lettersAndSpaces(lastName)) {
        this.newContactFormErrors.contactLastName = true;
    } else {
        this.newContactFormErrors.contactLastName = false;
    }

    if (Validate.isEmpty(email) || !Validate.emailRegex.test(email)) {
        this.newContactFormErrors.contactEmail = true;
    } else {
        this.newContactFormErrors.contactEmail = false;
    }

    // If there are any errors at this stage, Don't add
    if (this.newContactFormErrors.contactFirstName || this.newContactFormErrors.contactLastName || this.newContactFormErrors.contactEmail) {
        return
    }

    // Reset errors, just in case there were previous erros that we now know have been resolved
    this.resetContactFormErrors();
    this.addContactLoading = true;
    // If all is valid, send a request to create the new contact
    this.userService.addUserToAccount([{firstName, lastName, email, role: 'FULL'}], 'FULL', accountId)
        .subscribe(
            (response: any) => {
                this.addContactLoading = false;

                // Reset the add contact form so that the user can add more
                this.newContactForm.patchValue({
                    contactFirstName: '',
                    contactLastName: '',
                    contactEmail: '',
                });

                // If the new contact's email address is already in the on-page list do nothing
                if (_.find(this.contacts[accountId], {email})) {
                    return;
                } else {
                    // If the request is succcessful, add the new contact to the list of contacts
                    this.contacts[accountId].push({
                        accountId,
                        email,
                        firstName,
                        groupTag: 'FULL',
                        lastName,
                        provTaxManager: 0,
                                                    provTaxPaymentsContact: 0,
                                                    userId: response.userId,
                                                    //transactionContactId,
                    });
                }
            },
            error => {
                console.log("Error: " + error);
                const message = new Message();
                message.type = MessageType.ERROR;
                message.message = 'An error has occurred adding your contact. If the problem persists please contact us.';
                this.messagingService.emitMessage(message);
            }
        )
}

В консоли браузера я вижу следующий вывод на вкладке Network-> Preview:

array:9 [
"userId" => 9561
"title" => null
"firstName" => "Shane"
"lastName" => "Williams"
"workPhone" => null
"mobilePhone" => null
"email" => "shane@williams.com"
"userTypeId" => 3
"login" => array:3 [
"loginId" => 9449
"loginName" => "shane@williams.com"
"userId" => 9561
]
]

Это показывает, что данные, которые я ввел в форму, были собраны, и был назначен новый идентификатор пользователя.

Этот вывод исходит из dd(), который у меня есть в функции addAccountUser() PHP:

public function addAccountUser( AddAccountUsersRequest $request )
{
  $users = $request->input('users');
  $type = $request->input('type');
  $accountId = $request->input('accountId');

  $userType = $type == 'taxfirm-agent' ? UserType::where('userTypeTag', 'AGENT')->first() : UserType::where('userTypeTag', 'DIRECT')->first();
  $messages = array();
  $hasWarningMessages = false;

  try
  {
      DB::beginTransaction();

        foreach ($users as $userRaw)
        {

              $details = array(
                  'firstName' => $userRaw['firstName'],
                  'lastName'  => $userRaw['lastName'],
                  'email'     => $userRaw['email'],
                  'password'  => uniqid(),
                  'userTypeId' => $userType->userTypeId,
                  'accountId' => (!empty($accountId)) ? $accountId : null
              );
        $propertyValues = array();

        // Adding tax agent
        if ($type == 'taxfirm-agent') {
            $group = $userRaw['role'];
            $rv = $this->addTaxfirmAgent($details, $group);
        }
        else if($type == 'taxfirm-direct') {
            $rv = $this->addTaxfirmDirectContact($details);
        }
        else {
            $group = $userRaw['role'];
            $rv = $this->addTaxpayerDirectContact($details, $group);
        }

        DB::commit();
        dd($rv['user']->toArray()); 

        if ($rv['status'] !== 'SUCCESS') {
            if (!isset($messages[$rv['status']])) {
              $messages[$rv['status']] = array(
                'message' => StatusMessage::getMessage($rv['status']),
                'data' => [],
            //dd($messages);
              );
            }

            $messages[$rv['status']]['data'][] = [$userRaw['email'], ucfirst($userRaw['firstName']), ucfirst($userRaw['lastName'])];
        //dd($messages); // success is true at this point, users are null


            if (!$hasWarningMessages)
            {
              $hasWarningMessages = true;
            }
        }
        }
    }
      catch(\Exception $e)
      {
          DB::rollback();
        return response()->json(array(
          'success' => false,
          'exceptionCode' => $e->getCode(),
          'exceptionMessage' => $e->getMessage().' - '.$e->getFile().' - '.$e->getLine(),
          'userId' => $userId // Try returning the userId too...
        ), 400);
      }

      $outputMsg = array();
      foreach ($messages as $value) {
        $outputMsg[] = $value;
      }
      //dd($users);

      return response()->json(array(
        'success' => true,
        'hasWarningMessages' => $hasWarningMessages,
        'result' => $outputMsg,
        //'users' => $rv['user']->user, /*ERF(18/09/2018 @ 1630) Change to userId */
        'userId' => $rv['user']->userId,
      ));
    }

Я не до конца понимаю, как здесь взаимодействуют JavaScript, PHP и HTTP, или почему отладка PHP показывает, что новый контакт успешно создан, и все же я все еще получаю ошибку вбраузер.

Кто-нибудь может указать мне правильное направление здесь?Почему создается впечатление, что контакт создается, и все же я получаю сообщение об ошибке, а также то, что контакт не отображается в раскрывающемся списке, как я ожидал?

Редактировать

Итак, я думаю, что проблема, с которой я здесь сталкиваюсь, не связана с самим PHP - так как эта функция, кажется, возвращает правильную информацию (вывод консоли, полученный при добавлении строки dd($rv['user']->toArray()) в концефункция показала все детали для пользователя, которого я только что правильно добавил), а скорее для Angular, который должен обновлять интерфейс, для отображения нового пользователя в раскрывающемся списке.

Эта функцияопределяется следующим образом:

this.userService.addUserToAccount([{firstName, lastName, email, role: 'FULL'}], 'FULL', accountId)
.subscribe(
    (response: any) => {
        this.addContactLoading = false;

        // Reset the add contact form so that the user can add more
        this.newContactForm.patchValue({
            contactFirstName: '',
            contactLastName: '',
            contactEmail: '',
        });

        // If the new contact's email address is already in the on-page list do nothing
        if (_.find(this.contacts[accountId], {email})) {
            return;
        } else {
            // If the request is succcessful, add the new contact to the list of contacts
            this.contacts[accountId].push({
                accountId,
                email,
                firstName,
                groupTag: 'FULL',
                lastName,
                provTaxManager: 0,
                provTaxPaymentsContact: 0,
                userId: response.userId,
                //transactionContactId,
            });
       }
    },
    error => {
        console.log("Error: " + error);
        const message = new Message();
        message.type = MessageType.ERROR;
        message.message = 'An error has occurred adding your contact. If the problem persists please contact us.';
        this.messagingService.emitMessage(message);
    }
)

Я думаю, мне нужно добавить вызов для перезагрузки этого элемента страницы в конце оператора else в этой функции ... Как бы я это сделал?

Редактировать

Итак, кажется, что, хотя контакт кажется созданным, ответ HTTP, который я получаю, на самом деле является ошибкой - как я вижу сообщение An error has occurred adding your contact. If the problem persists please contact us.в браузере ... WHy это ответ HTTP не удается?Как я могу решить эту проблему?

Я добавил console.log(), чтобы отобразить ошибку в консоли, и она показывает следующий вывод:

непарсируемый ответ

Ошибка: SyntaxError: Неожиданный токен <в JSON в позиции 0 </p>

Я не понимаю, откуда возникает эта ошибка ... есть идеи?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...