google sheets angular 4写入数据显示错误"代码":403,↵" message":"请求的认证范围不足。"

时间:2018-03-24 20:12:09

标签: angular typescript google-sheets-api

ngOnInit() {
    this.onLoad();
    //called after the constructor and called  after the first ngOnChanges() 
}

initClient() {
    console.log('initClient called')
    gapi.client.init({
        'apiKey': 'APIKEY',
        'clientId': 'CLIENTID',
        'scope': [
            "https://www.googleapis.com/auth/analytics.readonly",
            "https://www.googleapis.com/auth/analytics",
            "https://www.googleapis.com/auth/spreadsheets",
            "https://www.googleapis.com/auth/drive.metadata.readonly",
            "https://www.googleapis.com/auth/drive",
        ].join(" "),
        'discoveryDocs': ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest']
    }).then(function() {
        this.GoogleAuth = gapi.auth2.getAuthInstance();

        // Listen for sign-in state changes.
        this.GoogleAuth.isSignedIn.listen(this.updateSigninStatus);
        this.updateSignInStatus(gapi.auth2.getAuthInstance().isSignedIn.get());

    });
}

ngAfterViewInit() {
    this.onLoad()
    this.sendAuthorizedApiRequest(this.currentApiRequest)
}
onLoad() {
    console.log('On load init');

    gapi.load('client', function() {
        gapi.client.init({
            'apiKey': 'APIKEY',
            'clientId': 'CLIENTID',
            'scope': [
                "https://www.googleapis.com/auth/analytics.readonly",
                "https://www.googleapis.com/auth/analytics",
                "https://www.googleapis.com/auth/spreadsheets",
                "https://www.googleapis.com/auth/drive.metadata.readonly",
                "https://www.googleapis.com/auth/drive",
            ].join(" "),
            'discoveryDocs': ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest']
        }).then(function() {
            this.GoogleAuth = gapi.auth2.getAuthInstance();

            // Listen for sign-in state changes.
            this.GoogleAuth.isSignedIn.listen(this.updateSigninStatus);
            this.updateSignInStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
        });

    });

}

handleClientLoad() {
    gapi.load('client:auth2', this.initClient);
}




onGoogleSignInSuccess = (event: GoogleSignInSuccess) => {
    this._zone.run(() => {
        let googleUser: gapi.auth2.GoogleUser = event.googleUser;
        let id: string = googleUser.getId();
        let profile: gapi.auth2.BasicProfile = googleUser.getBasicProfile();
        let tokenDetails: gapi.auth2.AuthResponse = googleUser.getAuthResponse();
        this.profile = profile.getName();
        this.token = tokenDetails.access_token;
        console.log('ID: ' +
            profile
            .getId()); // Do not send to your backend! Use an ID token instead.
        console.log('Name: ' + profile.getName());
        this.userName = profile.getName();
        this.dp = profile.getImageUrl();
        console.log('userName: ' + this.userName);
        console.log('token: ' + this.token);

        // this.router.navigate['/Dashboard'];
    });
}




readExcel() {
    this.http.get(`https://sheets.googleapis.com/v4/spreadsheets/SHEETID/values/Sheet1!A1:D10?key=APIKEY`).map((response: Response) => {
        console.log(response.json());
        this.excelObj = response.json();
        console.log(this.excelObj);
        console.log(this.excelObj.values[0]);
        this.excelHeaders = this.excelObj.values[0];

        // for chacking entire first column from google spreadsheet 
        for (let i = 1; i < this.excelObj.values.length; i++) {
            this.itemNoArray.push(this.excelObj.values[i][0])
        }
        console.log(this.itemNoArray)

        for (let i = 1; i < this.excelObj.values.length; i++) {
            if (this.excelObj.values[i][1] == 'ON') {

                this.excelObj.values[i][1] = true;
            }
            if (this.excelObj.values[i][1] == 'OFF') {

                this.excelObj.values[i][1] = false;
            }
            this.statusColumn.push(this.excelObj.values[i][1])
        }
        console.log(this.statusColumn)
        response.json();
    }).subscribe();
}




//step2


/**
 * Store the request details. Then check to determine whether the user
 * has authorized the application.
 *   - If the user has granted access, make the API request.
 *   - If the user has not granted access, initiate the sign-in flow.
 */
sendAuthorizedApiRequest(requestDetails) {
    console.log('sendAuthorizedApiRequest');
    this.currentApiRequest = requestDetails;
    if (this.isAuthorized) {

        // Make API request
        // gapi.client.request(requestDetails)
        gapi.client.request(requestDetails)
        // Reset currentApiRequest variable.
        this.currentApiRequest = {};
    } else {
        this.GoogleAuth.signIn();
        console.log('signin()');

    }
}

/**
 * Listener called when user completes auth flow. If the currentApiRequest
 * variable is set, then the user was prompted to authorize the application
 * before the request executed. In that case, proceed with that API request.
 */
updateSigninStatus(isSignedIn) {
    console.log('updateSigninStatus()');

    if (isSignedIn) {
        this.isAuthorized = true;
        if (this.currentApiRequest) {
            this.sendAuthorizedApiRequest(this.currentApiRequest);
        }
    } else {
        this.isAuthorized = false;
    }
}




writeExcel() {

    for (let i = 1; i < this.excelObj.values.length; i++) {
        if (this.excelObj.values[i][1] == true) {

            this.excelObj.values[i][1] = 'ON';
        }
        if (this.excelObj.values[i][1] == false) {

            this.excelObj.values[i][1] = 'OFF';
        }
        this.statusColumn.push(this.excelObj.values[i][1])
    }
    console.log('excelObj to be sent for Write', this.excelObj);

    let headers = new Headers();
    let authToken = this.token;
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization', `Bearer ${authToken}`);
    let options = new RequestOptions({
        headers: headers
    });
    let url = `https://sheets.googleapis.com/v4/spreadsheets/SHEETID/values/Sheet1!A1:D10?valueInputOption=USER_ENTERED`;

    this.http
        .put(url, JSON.stringify(this.excelObj), options)
        .map((response: Response) => {
            console.log(response.json());
            this.excelObj = response.json();
            console.log(this.excelObj);
            response.json();
        }).subscribe();
    // this.readExcel();
}




getUserDetails() {
    console.log('from service', this.profile.ig)
   }
}

即使我添加了所有范围并在Google API控制台中激活了所有API和客户端,也会出现身份验证范围错误 错误是错误&#34;代码&#34;:403,↵&#34;消息&#34;:&#34;请求的认证范围不足。&#34;

我尝试检查令牌,我使用的令牌是API令牌,不知何故,它与我从谷歌控制台检索以测试API的令牌不同。但是,要阅读excel,我的Google API令牌可以正常运行

0 个答案:

没有答案