【问题标题】:Google Sheets API with Ionic带有 Ionic 的 Google 表格 API
【发布时间】:2020-11-04 12:33:49
【问题描述】:

我想使用google sheets api 从电子表格中检索单元格公式。我做了凭证密钥等的配置。然后我去了google提到的javascript设置。但是出现错误 cannot find gapi ,所以我这样做了 solution 并且它有效。但现在我收到错误

“typeof client”类型上不存在属性“sheets”。

也经历了这个article,但没有多大帮助。 以下是我的实现。

Home.ts

readFromSpreadSheet() {
    gapi.client.sheets.spreadsheets.values.get({
      spreadsheetId: 'XXXIDXXX',
      range: 'Sheet1!A1:D7'
    }).then((response) => {
      var result = response.result;
      var numRows = result.values ? result.values.length : 0;
      console.log('${numRows} rows retrieved.');
    });
  }

client_secret.json

{"web":{"client_id":"XXX","project_id":"XXX","auth_uri":"XXX","token_uri":"https://accounts.google.com/o/oauth2/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"XXXXX"}}

quickstart.html

<!DOCTYPE html>
<html>
  <head>
    <title>Google Sheets API Quickstart</title>
    <meta charset='utf-8' />
  </head>
  <body>
    <p>Google Sheets API Quickstart</p>

    <!--Add buttons to initiate auth sequence and sign out-->
    <button id="authorize-button" style="display: none;">Authorize</button>
    <button id="signout-button" style="display: none;">Sign Out</button>

    <pre id="content"></pre>

    <script type="text/javascript">
      // Client ID and API key from the Developer Console
      var CLIENT_ID = 'XXXX';
      var API_KEY = 'XXX';

      // Array of API discovery doc URLs for APIs used by the quickstart
      var DISCOVERY_DOCS = ["https://sheets.googleapis.com/$discovery/rest?version=v4"];

      // Authorization scopes required by the API; multiple scopes can be
      // included, separated by spaces.
      var SCOPES = "https://www.googleapis.com/auth/spreadsheets.readonly";

      var authorizeButton = document.getElementById('authorize-button');
      var signoutButton = document.getElementById('signout-button');

      /**
       *  On load, called to load the auth2 library and API client library.
       */
      function handleClientLoad() {
        gapi.load('client:auth2', initClient);
      }

      /**
       *  Initializes the API client library and sets up sign-in state
       *  listeners.
       */
      function initClient() {
        gapi.client.init({
          apiKey: API_KEY,
          clientId: CLIENT_ID,
          discoveryDocs: DISCOVERY_DOCS,
          scope: SCOPES
        }).then(function () {
          // Listen for sign-in state changes.
          gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

          // Handle the initial sign-in state.
          updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
          authorizeButton.onclick = handleAuthClick;
          signoutButton.onclick = handleSignoutClick;
        });
      }

      /**
       *  Called when the signed in status changes, to update the UI
       *  appropriately. After a sign-in, the API is called.
       */
      function updateSigninStatus(isSignedIn) {
        if (isSignedIn) {
          authorizeButton.style.display = 'none';
          signoutButton.style.display = 'block';
          listMajors();
        } else {
          authorizeButton.style.display = 'block';
          signoutButton.style.display = 'none';
        }
      }

      /**
       *  Sign in the user upon button click.
       */
      function handleAuthClick(event) {
        gapi.auth2.getAuthInstance().signIn();
      }

      /**
       *  Sign out the user upon button click.
       */
      function handleSignoutClick(event) {
        gapi.auth2.getAuthInstance().signOut();
      }

      /**
       * Append a pre element to the body containing the given message
       * as its text node. Used to display the results of the API call.
       *
       * @param {string} message Text to be placed in pre element.
       */
      function appendPre(message) {
        var pre = document.getElementById('content');
        var textContent = document.createTextNode(message + '\n');
        pre.appendChild(textContent);
      }

      /**
       * Print the names and majors of students in a sample spreadsheet:
       * https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
       */
      function listMajors() {
        gapi.client.sheets.spreadsheets.values.get({
          spreadsheetId: 'XXXIDXXX',
          range: 'Class Data!A2:E',
        }).then(function(response) {
          var range = response.result;
          if (range.values.length > 0) {
            appendPre('Name, Major:');
            for (i = 0; i < range.values.length; i++) {
              var row = range.values[i];
              // Print columns A and E, which correspond to indices 0 and 4.
              appendPre(row[0] + ', ' + row[4]);
            }
          } else {
            appendPre('No data found.');
          }
        }, function(response) {
          appendPre('Error: ' + response.result.error.message);
        });
      }

    </script>

    <script async defer src="https://apis.google.com/js/api.js"
      onload="this.onload=function(){};handleClientLoad()"
      onreadystatechange="if (this.readyState === 'complete') this.onload()">
    </script>
  </body>
</html>

不知道如何处理 quickstart.html 。我只更改了 CLIENT_ID 和 API_KEY

$ 离子信息

cli 包:(/usr/local/lib/node_modules)

@ionic/cli-utils  : 1.19.2
ionic (Ionic CLI) : 3.20.0

全局包:

cordova (Cordova CLI) : 8.0.0

本地包:

@ionic/app-scripts : 3.1.10
Cordova Platforms  : none
Ionic Framework    : ionic-angular 3.9.2

系统:

ios-deploy : 1.9.2
Node       : v8.11.1
npm        : 6.0.0
OS         : macOS High Sierra
Xcode      : Xcode 9.1 Build version 9B55

环境变量:

ANDROID_HOME : not set

杂项:

backend : pro

请建议将 google 电子表格 api 与 ionic 集成的步骤或建议一些有用的文章。

【问题讨论】:

  • 您使用的是哪个 ionic 版本?
  • @PareshGami 我在我的问题中添加了离子信息。请看一看。

标签: javascript ionic-framework google-spreadsheet-api


【解决方案1】:

尝试一切之后。我得到了答案!

它是:

gapi.client 不支持 Cordova 应用

https://github.com/google/google-api-javascript-client/issues/334

支持的环境:

https://developers.google.com/api-client-library/javascript/start/start-js#supported-environments

【讨论】:

    【解决方案2】:

    在我的项目中,我使用了 Ionic 和 React。我遵循了这些步骤。

    1. 在项目目录运行命令
    npm install @types/gapi
    npm install @types/gapi.client
    npm install @types/gapi.client.sheets
    npm install @types/gapi.auth2
    
    1. package.json 中使用typestypeRoots
    { 
      // ... 
      "types":["gapi"], 
      "typeRoots":["node_modules/@types"], 
      // ...
    }  
    
    1. project_directory/src/index.html
    <script async defer src="https://apis.google.com/js/api.js" type="text/javascript"/> 
    
    1. .tstsx 文件类型中,var gapi=window.gapi;

    这将在 ionic localhost 开发服务器中正常工作 要在 android 中使用,您必须执行更多步骤。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-17
      • 2012-12-23
      • 1970-01-01
      相关资源
      最近更新 更多