代码之家  ›  专栏  ›  技术社区  ›  Noble-Surfer

PHP-在PHP、Angular和HTTP之间传递信息有问题吗?

  •  0
  • Noble-Surfer  · 技术社区  · 7 年前

    我在一个Laravel PHP站点上工作,在试图将用户添加到表中的单元格时出错

    错误显示:

    添加联系人时出错。如果问题仍然存在,请与我们联系。

    在尝试从下拉列表中选择新用户时,会在浏览器地址栏正下方弹出几秒钟的红色“功能区”中显示。

    我见过一些类似的 questions 就这样,但看不出任何答案如何适用于这里发生的事情。。。

    在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() 按下“添加联系人”按钮时调用的函数在名为tax-reminder.ts的Typescript文件中定义,除了处理前端浏览器的情况外,它还调用函数 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);
                }
            )
    }
    

    在浏览器控制台中,我可以在“网络”->“预览”选项卡中看到以下输出:

    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
    ]
    ]
    

    这表明我在表单中输入的详细信息已经收集,并且分配了新的用户ID。

    输出来自 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()) 在函数的末尾显示了我刚刚正确添加的用户的所有细节),而不是显示应该更新前端的角度,以便在下拉列表中显示新用户。

    该函数定义如下:

    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. 浏览器中的消息。。。为什么HTTP响应失败?我该怎么解决?

    我加了一个 console.log() 要在控制台中显示错误,它将显示以下输出:

    不可原谅的反应

    错误:SyntaxError:位置0处的JSON中出现意外标记<

    我不明白这个错误是从哪里来的。。。有什么想法吗?

    0 回复  |  直到 7 年前
    推荐文章