You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular2/JavaScript中通过API使用Google Forms并处理表单提交需求

Hey there! Let’s walk through each of your questions about integrating Google Forms into your Angular2/JavaScript app—here’s what you need to know:

1. How to Use Google Forms via API in Angular2/JavaScript?

First off, Google provides an official Google Forms API that lets you create and customize forms programmatically. Here’s how to get started:

Setup Steps:

  • Have your advertisers enable the Google Forms API and Google Drive API in their Google Cloud Console (your app needs access to these to create forms linked to their accounts).
  • Implement OAuth 2.0 authentication so advertisers can grant your app permission to manage forms on their behalf. For Angular, you can use the gapi client library directly or wrap it in a reusable service.

Example Code (JavaScript/Angular):

// Load Google API client and auth library
gapi.load('client:auth2', async () => {
  await gapi.client.init({
    apiKey: 'YOUR_APP_API_KEY',
    clientId: 'YOUR_OAUTH_CLIENT_ID',
    discoveryDocs: ["https://forms.googleapis.com/$discovery/rest?version=v1"],
    scope: 'https://www.googleapis.com/auth/forms.body https://www.googleapis.com/auth/drive.file'
  });

  // 1. Create a new form
  const formResponse = await gapi.client.forms.forms.create({
    resource: {
      info: {
        title: 'Gen Z Tech Interests Survey',
        description: 'Help us tailor our marketing to your interests!'
      }
    }
  });
  const formId = formResponse.result.formId;
  console.log('Created form with ID:', formId);

  // 2. Add custom questions (age group, gender, interests)
  await gapi.client.forms.batchUpdate({
    formId: formId,
    resource: {
      requests: [
        {
          createItem: {
            item: {
              title: 'What\'s your age group?',
              questionItem: {
                question: {
                  choiceQuestion: {
                    type: 'RADIO',
                    options: [
                      {value: '13-17'}, {value: '18-24'}, {value: '25-34'}, {value: '35+'}
                    ]
                  }
                }
              }
            },
            location: {index: 0}
          }
        },
        // Add gender and interest questions using similar syntax
      ]
    }
  });
});

In Angular, wrap this logic in a GoogleFormsService so you can inject it into components where advertisers create surveys.

2. How to Retrieve Response Data via API After Users Submit?

Once users fill out the form, you can pull responses using the Forms API, or set up a real-time webhook for instant updates:

Option 1: Poll the Forms API

Use the forms.responses.list endpoint to fetch all submissions. You’ll need the forms.responses.readonly scope:

async function fetchFormResponses(formId) {
  const response = await gapi.client.forms.responses.list({formId});
  const submissions = response.result.responses;
  
  submissions.forEach(submission => {
    console.log('User response ID:', submission.responseId);
    // Access answers via submission.answers (keyed by question ID)
    const ageAnswer = submission.answers['QUESTION_ID'].textAnswers.answers[0].value;
  });
}

Option 2: Real-Time Webhook with Google Apps Script

For instant updates (no polling), use a Google Apps Script trigger that sends data to your app when a form is submitted:

// In Google Apps Script (linked to the form)
function onFormSubmit(e) {
  const response = e.response;
  const payload = {
    formId: e.source.getId(),
    responseId: response.getId(),
    answers: response.getItemResponses().map(item => ({
      question: item.getItem().getTitle(),
      answer: item.getResponse()
    }))
  };

  // Send data to your app's API endpoint
  UrlFetchApp.fetch('https://your-app.com/api/form-submit', {
    method: 'POST',
    contentType: 'application/json',
    payload: JSON.stringify(payload)
  });
}

Set up an onFormSubmit trigger in Apps Script to activate this function automatically when someone submits the form.

3. How to Receive Form Completion Confirmation to Reward Users?

You need a reliable way to detect when a user finishes the form—here are the best approaches:

Option 1: Custom Redirect URL

When creating the form, set a redirect URL that users are sent to after submission. Use the Forms API to configure this:

await gapi.client.forms.batchUpdate({
  formId: formId,
  resource: {
    requests: [
      {
        updateFormInfo: {
          info: {
            confirmationMessage: 'Thanks! We\'re redirecting you to claim your reward.',
            customRedirectUrl: `https://your-app.com/claim-reward?responseId=${formId}-USER_RESPONSE_ID`
          },
          updateMask: 'confirmationMessage,customRedirectUrl'
        }
      }
    ]
  }
});

On your app’s /claim-reward page, verify the responseId by checking it against the Forms API, then trigger the reward (e.g., add points to the user’s account).

Option 2: Use the Apps Script Webhook

Leverage the same webhook from question 2—when your app receives the submission data, match it to the logged-in user (you’ll need to pass a user ID in the form or track it via your app’s session) and immediately grant the reward. Just make sure to validate the request is coming from Google to prevent fraud.

Option 3: Embed Form with URL Monitoring (Less Reliable)

If you embed the form in an iframe in your Angular app, you can monitor the iframe’s URL for submission indicators (like /formResponse in the URL). Note: This has cross-origin restrictions, so it’s a fallback option:

// In your Angular component
import { ViewChild, ElementRef, AfterViewInit } from '@angular/core';

export class FormEmbedComponent implements AfterViewInit {
  @ViewChild('formIframe') formIframe!: ElementRef;

  ngAfterViewInit() {
    setInterval(() => {
      try {
        const iframeUrl = this.formIframe.nativeElement.contentWindow.location.href;
        if (iframeUrl.includes('/formResponse')) {
          // User submitted the form—trigger reward logic
          this.claimUserReward();
        }
      } catch (e) {
        // Cross-origin error is expected, ignore it
      }
    }, 1000);
  }

  claimUserReward() {
    // Your reward logic here
  }
}

内容的提问来源于stack exchange,提问作者arkhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:17:03