J
J
JIakki2016-02-16 16:31:54
Angular
JIakki, 2016-02-16 16:31:54

How to get a reference to a class?

I have a Service to work with gmail api,

import {Injectable} from 'angular2/core';

@Injectable()

export class Gmail {
  client_id:string = '444353411828-gqbdqsfcohfqf1s9q71bkuhh16tui37b.apps.googleusercontent.com';
  scopes:Array<string> = ['https://www.googleapis.com/auth/gmail.readonly'];

  checkAuth() {
    console.log(this) // тут this == Gmail
    gapi.auth.authorize({
      'client_id': this.client_id,
      'scope': this.scopes.join(' '),
      'immediate': true
    }, this.handleAuthResult);

  }

  handleAuthResult(authResult) {
    console.log(this) // а тут уже на Window
    var authorizeDiv = document.getElementById('authorize-div');
    if (authResult && !authResult.error) {
      authorizeDiv.style.display = 'none';
      this.loadGmailApi();
    } else {
      authorizeDiv.style.display = 'inline';
    }
  }

  handleAuthClick(event) {
    gapi.auth.authorize({
      client_id: this.client_id,
      scope: this.scopes,
      immediate: false
    }, this.handleAuthResult);

    return false;
  }


  loadGmailApi() {
    gapi.client.load('gmail', 'v1', this.listLabels);
  }

  listLabels() {
    var request = gapi.client.gmail.users.labels.list({
      'userId': 'me'
    });

    request.execute(function(resp) {
      var labels = resp.labels;
      this.appendPre('Labels:');

      if (labels && labels.length > 0) {
        for (let i = 0; i < labels.length; i++) {
          var label = labels[i];
          this.appendPre(label.name)
        }
      } else {
        this.appendPre('No Labels found.');
      }
    });
  }

  appendPre(message) {
    var pre = document.getElementById('output');
    var textContent = document.createTextNode(message + '\n');
    pre.appendChild(textContent);
  }
}

and the Auth component
import {Component} from 'angular2/core';
import {Gmail} from "../services/gmail.js";

@Component({
  selector: 'auth'
})

export class Auth {

  constructor(public gmail:Gmail){
    gmail.checkAuth();
  }
}

But when the checkAuth method of the Gmail class is run, the this in the method refers to Window
I think when this.handle AuthResult is called, this does not refer to Gmail internally, but how can I fix this :?
Thanks in advance

Answer the question

In order to leave comments, you need to log in

1 answer(s)
_
_ _, 2016-02-16
@AMar4enko

this.handleAuthResult.bind(this) or

gapi.auth.authorize({
      'client_id': this.client_id,
      'scope': this.scopes.join(' '),
      'immediate': true
    }, response => this.handleAuthResult(response));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question