Доступ к параметрам конструктора внутри функции входа в Google Angular 2

0

Я переводил знак google в javascript для машинописного текста, и он работает, проблема, с которой я сталкиваюсь, - я не могу получить доступ к переменной _router внутри функции входа в google. Внутри attachSignin() функция Я пытаюсь получить доступ к _router: Параметр маршрутизатора из конструктора, и я получаю, что это не определено.

это мой код

import {Component, NgZone} from "angular2/core";
import {ToastsManager } from 'ng2-toastr/ng2-toastr';
import {Router, ROUTER_PROVIDERS} from 'angular2/router'

// Google login API namespace
declare var gapi: any;

@Component({
    selector: "sous-app",
    templateUrl: "app/login/login.html",
    providers: [ToastsManager, ROUTER_PROVIDERS]
})
export class Login {
    googleLoginButtonId = "google-login-button";
    userAuthToken = null;
    userDisplayName = "empty";
    auth2 = null;
    self = this;


    constructor(
        public _router: Router) { }

    // Angular hook that allows for interaction with elements inserted by the
    // rendering of a view.
    ngAfterViewInit() {
        var loginProxy = $.proxy(this.attachSignin, this);
        var redirectToPolls = $.proxy(this.redirectToPolls, this);
        gapi.load('auth2', function () {
            // Retrieve the singleton for the GoogleAuth library and set up the client.
            self.auth2 = gapi.auth2.init({
                client_id: '718161509287-jdpqsuebcoteh847krjn0m1odnbo5i3q.apps.googleusercontent.com',
                cookiepolicy: 'single_host_origin',
                // Request scopes in addition to 'profile' and 'email'
                //scope: 'additional_scope'
            });
            loginProxy(document.getElementById('customBtn'));
        });

    }


    attachSignin = (element) => {

        var navigate = false;
        console.log(element.id);
        self.auth2.attachClickHandler(element, {},
            function (googleUser) {

                var profile = googleUser.getBasicProfile();
                console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
                console.log('Name: ' + profile.getName());
                console.log('Image URL: ' + profile.getImageUrl());
                console.log('Email: ' + profile.getEmail());

                //HERE I WANT TO ACCESS ROUTER
                _router.navigate(['Polls']);



                console.log(googleUser.getAuthResponse().id_token);



            }, function (error) {
                alert(JSON.stringify(error, undefined, 2));
            });

    }

}
Теги:
angular
angular2-routing
google-signin

1 ответ

2
Лучший ответ

изменить function() на () =>

    self.auth2.attachClickHandler(element, {},
        (googleUser) => {
  • 0
    Теперь он не дал мне неопределенного изменения URL браузера, но не переходил к нему. Как я могу форсировать навигацию?
  • 0
    Это также должно работать для вас stackoverflow.com/a/36171639/217408 Оберните код в обратный вызов, который zone.run(...) библиотекой Google в zone.run(...)
Показать ещё 14 комментариев

Ещё вопросы

Сообщество Overcoder
Наверх
Меню