问题描述: 在Angular 6中,向Google Sheet发送的内容未定义。
解决方法:
import { GoogleSheetsService } from 'path/to/google-sheets.service';
import { Component } from '@angular/core';
import { GoogleSheetsService } from 'path/to/google-sheets.service';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
constructor(private googleSheetsService: GoogleSheetsService) { }
sendDataToGoogleSheet() {
const data = { name: 'John', age: 25 }; // 要发送到Google Sheet的数据
this.googleSheetsService.sendData(data).subscribe(
response => {
console.log(response); // 成功发送到Google Sheet的响应
},
error => {
console.log(error); // 发送到Google Sheet时的错误
}
);
}
}
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class GoogleSheetsService {
private readonly spreadsheetId = 'YOUR_SPREADSHEET_ID'; // Google Sheet的ID
private readonly range = 'Sheet1!A1:B'; // 要写入数据的范围
private readonly apiKey = 'YOUR_API_KEY'; // Google Sheets API的API密钥
constructor(private http: HttpClient) { }
sendData(data: any): Observable {
const url = `https://sheets.googleapis.com/v4/spreadsheets/${this.spreadsheetId}/values/${this.range}:append?valueInputOption=RAW&key=${this.apiKey}`;
const body = { values: [Object.values(data)] };
return this.http.post(url, body);
}
}
这样,当点击按钮时,将发送数据到Google Sheet,并在控制台中显示成功响应或错误。