Search code examples
angularangular2-routinggoogle-picker

Google Picker API + Angular2 getting Uncaught TypeError: Cannot read property 'handleAuthResult' of undefined


I'm integrating Google picker API in my application. I'm following the official documentation Google Picker API

google api js i included in my index.html page as suggested by docs

 <script type="text/javascript" src="https://apis.google.com/js/api.js"></script>

here is my div in html page :

<img src="../GoogleDrive.png(click)="onApiLoad()">  

here is my component code :

  onApiLoad() {
         let self = this;
         gapi.load('auth', {'callback': self.onAuthApiLoad});
         gapi.load('picker');
     }

     onAuthApiLoad() {
         let self = this;
         window.gapi.auth.authorize(                
                 {
                     'client_id': "clientid",
                     'scope': ['https://www.googleapis.com/auth/drive.readonly'],
                     'immediate': false
                 },
                 self.handleAuthResult);
     }

      handleAuthResult(authResult:any) {
         let self = this;
         if (authResult && !authResult.error) {
             oauthToken = authResult.access_token;
             self.createPicker(oauthToken);
         }
     }

     createPicker() {
         let self = this;
         if ( oauthToken) {
             var pickerBuilder = new google.picker.PickerBuilder();
             var picker = pickerBuilder
             .enableFeature(google.picker.Feature.NAV_HIDDEN)
             .setOAuthToken(oauthToken)
             .addView(google.picker.ViewId.DOCS_VIDEOS)
             .setDeveloperKey('apikey')
             .setCallback(self.pickerCallback)
             .build();
             picker.setVisible(true);
         }
     }

     pickerCallback(data) {
         let self = this;
         if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
             var doc = data[google.picker.Response.DOCUMENTS][0];
             self.downloadGDriveFile(doc.id , doc.name);
         }
     }

     downloadGDriveFile(fileId, name){
}

I'm getting Uncaught TypeError: Cannot read property 'handleAuthResult' of undefined. Can anyone please help me..


Solution

  • I think the load method is not giving the lexical this inside the callback, try to bind this to your method:

    gapi.load('auth', {'callback': self.onAuthApiLoad.bind(this)});